什么是`Vec :: new()`的默认类型?

Raj*_*jan 1 vector rust

我是Rust的新手.我知道Rust会在编译时预测绑定的类型.下面的代码编译并运行.

fn main() {
    let mut numbers = Vec::new();
    numbers.push(1);
}
Run Code Online (Sandbox Code Playgroud)

numbers矢量的默认类型是什么?

Mut*_*pus 11

Vec::new()依赖于其背景信息.当你向向量推送东西时,编译器知道"哦,这是我应该期待的那种对象".但是,由于您的示例是推送整数文字1,这似乎与整数文字的默认类型有关.

在Rust中,将根据上下文在编译时为无类型的整数文字赋值.例如:

let a = 1u8;
let b = 2;
let c = a + b;
Run Code Online (Sandbox Code Playgroud)

bc将是u8S; a + b分配b为相同的类型a,u8结果是操作的输出.

如果未指定类型,则编译器似乎选择i32(根据此操场实验).所以在你的具体例子中,如在操场上看到的,numbers将是一个Vec<i32>.


lje*_*drz 6

Rust 中的向量是泛型的,这意味着它们没有默认类型 - 除非默认情况下您的意思是Vec<T>(T是泛型类型参数) 或Vec<_>(_类型占位符)。

如果编译器没有找到任何相关的类型注解或无法使用类型推断推断元素类型,它将拒绝构建代码:

let mut numbers = Vec::new();

error[E0282]: type annotations needed
 --> src/main.rs:2:23
  |
2 |     let mut numbers = Vec::new();
  |         -----------   ^^^^^^^^ cannot infer type for `T`
  |         |
  |         consider giving `numbers` a type
Run Code Online (Sandbox Code Playgroud)

您可以通过尝试使用技巧找出变量的类型来进一步验证它:

let mut numbers = Vec::new();
let () = numbers;

error[E0308]: mismatched types
 --> src/main.rs:4:9
  |
3 |     let () = numbers;
  |         ^^ expected struct `std::vec::Vec`, found ()
  |
  = note: expected type `std::vec::Vec<_>` // Vec<_>
             found type `()`
Run Code Online (Sandbox Code Playgroud)