gpt4 book ai didi

rust - 数字数组(不是 Vec)的类型是什么?

转载 作者:行者123 更新时间:2023-11-29 08:26:56 25 4
gpt4 key购买 nike

我无法确定数组的正确类型(不是 Vec)。以下代码无法编译:

fn sum(a: [f32]) -> f32 {
return 3.0;
}

fn main() {
let x = [0.0, 1.0, 2.0];
print!("{}\n", sum(x));
}
error[E0277]: the trait bound `[f32]: std::marker::Sized` is not satisfied
--> src/main.rs:1:8
|
1 | fn sum(a: [f32]) -> f32 {
| ^ `[f32]` does not have a constant size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `[f32]`
= note: all local variables must have a statically known size

error[E0308]: mismatched types
--> src/main.rs:7:24
|
7 | print!("{}\n", sum(x));
| ^ expected slice, found array of 3 elements
|
= note: expected type `[f32]`
found type `[{float}; 3]`

suma 的合适类型是什么?

最佳答案

数组的类型是[ElementType;长度]

  • [i32; 10]
  • [字符; 16]
  • [u8; 3]
  • [字符串; 5]

令人惊讶的是,这并没有在 The Rust Programming Language 中直接调用, 除了在 operators and symbols appendix .要使它有用,您必须已经知道所需的语法!

但是,编译器确实会引导您找到正确的解决方案。花时间完整阅读 Rust 编译器的错误消息。它们通常非常好,而且大多数都付出了很多努力。查看错误中的注释;它告诉你你有什么类型:

  = note: expected type `[f32]`
found type `[{float}; 3]`

found type `[{float}; 3]`

您也可以print out the type of a variable :

let x: () = [0.0, 1.0, 2.0];

针对您的特定功能的修复:

fn sum(a: [f32; 3]) -> f32 {
3.0
}

另见:

关于rust - 数字数组(不是 Vec)的类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50936610/

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