【问题标题】:What is an underscore in Rust type? [duplicate]Rust 类型中的下划线是什么? [复制]
【发布时间】:2020-05-22 08:06:10
【问题描述】:

我是 Rust 初学者,请多多包涵。

如下图所示,VSCode rust-analyzer 插入了一个带有下划线“_”的类型。这是什么?

let a: [i32; _] = [3; 5];
// this is the same as
let a: [i32; _] = [3, 3, 3, 3, 3];

【问题讨论】:

    标签: rust rust-analyzer


    【解决方案1】:

    VS Code 在这里作弊。

    当需要类型时,_ 表示编译器必须推断类型。例如:

    let v: [_; 5] = [3; 5];
        //  ^ infers type for usage
    
    f(&v); // where f: fn(&[u8])
           // the previous type will be inferred to `u8`
    

    但是,这只有在需要 type 的情况下才有可能。 [T; _] 不是有效的 Rust:

    let foo: [i32; _] = [1, 2];
    

    给予

    error: expected expression, found reserved identifier `_`
     --> src/main.rs:2:20
      |
    1 | let foo: [i32; _] = [1, 2];
      |     ---        ^ expected expression
      |     |
      |     while parsing the type for `foo`
    

    但是 VS Code 无论如何都使用它来表达“我不知道这里的价值”,因为虽然这不是有效的 Rust,但它是一个很好理解的概念。

    另见:

    【讨论】:

      猜你喜欢
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 2013-10-13
      • 1970-01-01
      • 2015-04-18
      • 2017-11-07
      • 2011-09-03
      • 1970-01-01
      相关资源
      最近更新 更多