【问题标题】:What is the type for an array (not Vec) of numbers?数字数组(不是 Vec)的类型是什么?
【发布时间】:2018-06-20 22:10:50
【问题描述】:

我无法确定数组的正确类型(不是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]`

sum 中的a 的合适类型是什么?

【问题讨论】:

    标签: rust


    【解决方案1】:

    数组的类型是[ElementType; Length]

    • [i32; 10]
    • [char; 16]
    • [u8; 3]
    • [String; 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
    }
    

    另见:

    【讨论】:

    • 是否可以定义函数使其适用于任何长度? (不进入 Vec)某种模板或泛型?
    【解决方案2】:

    我正在添加 Shepmaster 的答案。

    你所做的,[f32],实际上是有效的语法。它表示在编译时大小未知的切片(元素列表)。它的问题是,如果在编译时不知道其大小,则无法将某些内容传递给函数。
    Shepmaster 建议的语法适用于固定大小的数组,因此可以使用。

    如果无法避免传递切片,则可以使用引用。引用始终具有固定大小,但可用于访问未调整大小的数据(我建议阅读 Rust 文档):

    // The ampersand means that the function takes a reference to a [f32]
    fn sum(a: &[f32]) -> f32 {
        return 3.0;
    }
    
    fn main() {
        let x = [0.0, 1.0, 2.0];
        print!("{}\n", sum(&x)); // Here, the ampersand makes a reference out of x
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-22
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      • 2021-08-18
      • 2018-08-27
      相关资源
      最近更新 更多