gpt4 book ai didi

vector - 如何在Vec 中将元素从x返回到y?

转载 作者:行者123 更新时间:2023-12-03 11:33:36 25 4
gpt4 key购买 nike

我有一个Vec的结构,我想从位置x到y:

fn main() {
#[derive(Debug)]
struct A {
name: String,
}

let x = A { name: "X".to_string() };
let y = A { name: "Y".to_string() };
let z = A { name: "Z".to_string() };

let v = vec!(x,y,z);

println!("{:?}", v[0..1]);
}
这是 Rust Playground link for it
我收到错误消息:
error[E0277]: the size for values of type `[A]` cannot be known at compilation time
--> src/main.rs:13:5
|
13 | println!("{:?}", v[0..1]);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
如何确保在编译时知道大小?我找不到任何明显的答案,因此我想我缺少一些基本知识。

最佳答案

改变

println!("{:?}", v[0..1]);

println!("{:?}", &v[0..1]);
Vec索引 Range会返回大小的 slice,但是当您在变量上使用 []时,编译器会自动取消引用返回的值(这只是语法糖),在这种情况下,这会导致切片的大小未定,因此必须将请引用它前面的内容,以重新调整其大小。
也可以看看:
  • Rust doesn't have a size known at compile-time
  • What is the return type of the indexing operation?
  • 关于vector - 如何在Vec <T>中将元素从x返回到y?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66155218/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com