假设我想在测试中将一个Vec<String>
与字面意义上的空列表进行比较。
(我知道在实践中可以检查is_empty()
,但我想了解Rust类型系统在这里的工作原理,并且我认为如果失败的话,断言相等性会给出更清晰的信息。)
如果我只是这样说:
let a: Vec<String> = Vec::new();
assert_eq!(a, []);
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)
我认为问题在于rustc无法确定我是指String
的空列表,还是&str
的空列表,或者其他什么?
我如何将所需的类型注释添加到[]
字面值中?
这取决于尚未稳定的类型注释功能,还是有一种稳定的方法来指定这个?
[""; 0]
。 - ramslök