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

时间:2018-04-17 03:38:35

标签: vector rust

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

fn main() {
    let mut numbers = Vec::new();
    numbers.push(1);
}

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

2 个答案:

答案 0 :(得分:11)

Vec::new()依赖于其背景信息。当你把东西推到矢量上时,编译器知道"哦,这是我应该期待的那种对象"。但是,由于您的示例正在推动整数文字1,这似乎与the default type of an integer literal.

相关

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

let a = 1u8;
let b = 2;
let c = a + b;

bc将为u8 s; a + bb指定为与a相同的类型,因此操作的输出为u8

如果未指定类型,编译器似乎选择i32(每this playground experiment)。因此,在您的具体示例中,如操场上所示,numbers将是Vec<i32>

答案 1 :(得分:4)

Rust中的向量是通用的,这意味着它们没有默认类型 - 除非默认情况下是Vec<T>T是泛型类型参数)或{{3} (_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

您可以尝试使用type placeholder

进一步验证
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 `()`
相关问题