获取错误“未实现 trait Sized"尝试从向量返回值时 [英] Getting the error "the trait Sized is not implemented" when trying to return a value from a vector

查看:33
本文介绍了获取错误“未实现 trait Sized"尝试从向量返回值时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to return the values of a vector:

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

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

I can't find out how to fix this.

推荐答案

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

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

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

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

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

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 是一种拥有数据的东西,可以让其他东西通过切片借用它.对于您的问题,您需要分配一些内存来存储值,而 Vec 会为您完成.然后您可以返回整个 Vec,将所有权转移给调用者.

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.

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

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
}

此外,您不需要在此处指定生命周期,并且我删除了您的 merged 声明中的冗余类型注释.

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

另见:

这篇关于获取错误“未实现 trait Sized"尝试从向量返回值时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆