Getting the error “the trait Sized is not implemented” when trying to return a value from a vector

前端 未结 1 1882
北海茫月
北海茫月 2020-12-10 15:21

I am trying to return the values of a vector:

fn merge<\'a>(left: &\'a [i32], right: &\'a [i32]) ->          


        
相关标签:
1条回答
  • 2020-12-10 15:54

    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.

    See also:

    • Is there any way to return a reference to a variable created in a function?
    • Why can fixed-size arrays be on the stack, but str cannot?
    • Why is `let ref a: Trait = Struct` forbidden?
    0 讨论(0)
提交回复
热议问题