gpt4 book ai didi

rust - 如何修复错误 E0277 : the trait bound `[usize]: std::marker::Sized` is not satisfied?

转载 作者:行者123 更新时间:2023-11-29 08:10:47 24 4
gpt4 key购买 nike

我正在尝试将一个数组传递给一个函数:

fn my_func(xs: [usize]) -> usize {
0
}

fn main() {
let arr = [329, 457, 657];
let res = my_func(inp);
}

我得到错误:

error[E0277]: the trait bound `[usize]: std::marker::Sized` is not satisfied
--> src/main.rs:1:12
|
1 | fn my_func(xs: [usize]) -> usize {
| ^^ `[usize]` does not have a constant size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `[usize]`
= note: all local variables must have a statically known size

我知道 these other questions但它们似乎不适用于我的简单情况。

如何修复错误?

最佳答案

您的问题(以及 & 解决您的问题的原因)是,切片在编译时 的大小未知。

有几种解决方法:

  1. 使用明确的长度

    fn foo(arr: [usize; 3]) { }

使用显式长度将告诉编译器数组有多大,并且现在可以决定为数组保留多少空间。

  1. 使用引用

    fn foo(arr: &[usize]) { }

指向切片的引用(实际上是一个胖指针),其大小在编译时已知(取决于您的体系结构,但通常是 32/64 位)。

  1. 使用堆分配

    fn foo(arr: Box<[usize]> { }

盒子是堆分配的元素(实际上是指针),因此大小也是已知的。

还有其他容器(RcArc、...)接受未调整大小的元素。您可以轻松地在源代码中发现它们,因为它们有一个需求 ?Sized他们的模板参数(参见 Box example )。

关于rust - 如何修复错误 E0277 : the trait bound `[usize]: std::marker::Sized` is not satisfied?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51650259/

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