rust - 尝试从向量返回值时出现错误 "the trait Sized is not implemented"

标签 rust

我正在尝试返回向量的值:

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

我收到错误信息:

error[E0277]: the size for values of type `[i32]` cannot be known at compilation time
 --> src/lib.rs:1:52
  |
1 | fn merge<'a>(left: &'a [i32], right: &'a [i32]) -> [i32] {
  |                                                    ^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `[i32]`
  = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
  = note: the return type of a function must have a statically known size

我不知道如何解决这个问题。

最佳答案

编译器告诉你不可能返回 [T] .

Rust 拥有向量 ( Vec<T> )、切片 ( &[T] ) 和固定大小的数组 ( [T; N] ,其中 N 是一个非负整数,如 6 )。

切片由指向数据的指针和长度组成。这就是你的leftright值是。但是,切片中没有指定的是谁最终拥有数据。切片只是从其他东西借用数据。你可以对待&作为数据被借用的信号。

A Vec是拥有数据并可以让其他事物通过切片借用它的事物。对于您的问题,您需要分配一些内存来存储值,并且 Vec为你做那件事。然后您可以返回整个 Vec , 将所有权转移给调用者。

具体的错误信息是指编译器不知道为[i32]类型分配多少空间,因为它永远不会直接分配。对于 Rust 中的其他事物,您会看到此错误,通常是当您尝试取消引用 trait 对象 时,但这与此处的情况明显不同。

这是您最可能想要的修复方法:

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

此外,你不需要在这里指定生命周期,我删除了你的merged上的冗余类型注释。声明。

另见:

关于rust - 尝试从向量返回值时出现错误 "the trait Sized is not implemented",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28175528/

相关文章:

linked-list - 遍历列表时,借用的 RefCell 持续时间不够长

rust - 如何从函数返回 Any?

rust - 尝试拆分字符串时,未为 `FnMut<(char,)>` 实现特征 `String`

copy - 如何轻松地将非 mut &[u8] 复制到 &mut [u8]

generics - "no field on type"泛型类型实现错误

rust - 如何将 Vec 解构为拥有所有权的变量?

for-loop - 在循环 block 外使用 enumerate 的索引

rust - 为什么我不能使用返回编译时常量的函数作为常量?

memory - 如何调整结构体的大小?

rust - 优化级别 `-Os` 和 `-Oz` 在 Rust 中有什么作用?