【问题标题】:What is the default type of `Vec::new()` in rust?rust 中 `Vec::new()` 的默认类型是什么?
【发布时间】:2018-04-17 03:38:34
【问题描述】:

我是 Rust 的新手。我了解 Rust 在编译时预测绑定的类型。下面的代码编译并运行。

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

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

【问题讨论】:

  • 我很想知道您使用的是什么编译器和/或您定义为“编译和运行”的内容。
  • 我的意思是rustc,我正在使用货物。
  • 编辑后的帖子中没有默认输入。它是Vec<u64>,你可以分辨出来,因为你调用的是u64::from_string,它是一个Result<u64,_>,而expect 会解开该值。
  • @E_net4 最初的问题与整数无关(并且没有明显的重复),但我认为提问者对 cme​​ts 感到沮丧;不过,我现在不知道如何处理这个问题。

标签: vector rust


【解决方案1】:

Vec::new() 依赖于其上下文来获取信息。当您将某些内容推送到向量时,编译器会知道“哦,这是我应该期待的那种对象”。但是由于您的示例正在推送整数文字1,这似乎与the default type of an integer literal.有关

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

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

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

如果没有指定类型,编译器似乎会选择i32(根据this playground experiment)。所以在你的具体例子中,正如在操场上看到的那样,numbers 将是一个Vec<i32>

【讨论】:

  • 这一行使上下文非常清晰“当你将一些东西推送到向量时,编译器知道“哦,这是我应该期待的那种对象”。非常准确的答案。
【解决方案2】:

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

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

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

您可以尝试使用a trick to find out the type of a variable 进一步验证:

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 `()`

【讨论】:

    猜你喜欢
    • 2019-09-18
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 2014-09-30
    • 1970-01-01
    相关资源
    最近更新 更多