Getting the error “error: the trait `core::marker:

2019-02-12 22:26发布

I am trying to return the values of a vector with the following code and. I am getting the error message.

fn merge<'a>(left: &'a [i32], right: &'a [i32]) -> [i32] {
    let mut merged: Vec<i32> = Vec::new();
    // push elements to merged
    *merged
}

test.rs:19:52: 19:57 error: the trait core::marker::Sized is not implemented for the type [i32] test.rs:19 fn merge<'a>(left: &'a [i32], right: &'a [i32]) -> [i32] {

And I can't for the life of me find out how I fix this

标签: rust
1条回答
姐就是有狂的资本
2楼-- · 2019-02-12 23:03

The compiler is telling you that it is impossible to return a [T].

Rust has owned vectors (Vec<T>), slices (&[T]) and fixed-size arrays ([T; n], where n is a non-negative integer like 6).

A slice is composed of a pointer to data and a length. This is what your left and right values are. However, what isn't specified in a slice is who ultimately owns the data. Slices just borrow data from something else. You can treat the & as a signal that the data is borrowed.

A Vec is one thing that owns data and can let other things borrow it via a slice. For your problem, you need to allocate some memory to store the values, and Vec does that for you. You can then return the entire Vec, transferring ownership to the caller.

The specific error message means that the compiler doesn't know how much space to allocate for the type [i32], because it's never meant to be allocated directly. You'll see this error for other things in Rust, usually when you try to dereference a trait object, but that's distinctly different from the case here.

Here's the most likely fix you want:

fn merge(left: &[i32], right: &[i32]) -> Vec<i32> {
    let mut merged = Vec::new();
    // push elements to merged
    merged
}

Additionally, you don't need to specify lifetimes here, and I removed the redundant type annotation on your merged declaration.

查看更多
登录 后发表回答