如何在 Rust 中注释空切片的类型?

poo*_*lie 7 unit-testing assert rust

假设我想Vec<String>在测试中将 a 与文字空列表进行比较。

(我知道在实践中我可以检查is_empty(),但我想了解 Rust 类型在这里是如何工作的,我认为如果失败,断言相等会给出更清晰的信息。)

如果我只是说

    let a: Vec<String> = Vec::new();
    assert_eq!(a, []);
Run Code Online (Sandbox Code Playgroud)

得到一个错误的是

error[E0282]: type annotations needed
 --> src/main.rs:3:5
  |
3 |     assert_eq!(a, []);
  |     ^^^^^^^^^^^^^^^^^^ cannot infer type
  |
  = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
Run Code Online (Sandbox Code Playgroud)

我认为问题是 rustc 无法判断我的意思是空列表String还是空列表&str或其他内容?

如何将所需的类型注释添加到[]文字上?

这是否取决于尚未稳定的类型归属特征,还是有一种稳定的方式来指定这一点?

poo*_*lie 7

一种方法是工程今天是as投指定的类型和长度:

assert_eq!(a, [] as [&str; 0]);
Run Code Online (Sandbox Code Playgroud)

  • 我可能会更快地找到以下解决方法,但感觉“不太纯粹”,因为我们提到了一个未使用的值: `[""; 0]`。 (3认同)