我正在尝试返回向量的值:
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
)。
切片由指向数据的指针和长度组成。这就是你的left
和 right
值是。但是,切片中没有指定的是谁最终拥有数据。切片只是从其他东西借用数据。你可以对待&
作为数据被借用的信号。
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/