问题
Suppose I want to compare a Vec<String>
to a literal empty list in a test.
(I'm aware that in practice I could check is_empty()
, but I'd like to understand how Rust typing works here, and I think asserting equality will give a clearer message if it fails.)
If I just say
let a: Vec<String> = Vec::new();
assert_eq!(a, []);
I get an error that
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)
I think the issue is that rustc can't tell whether I mean an empty list of String
, or an empty list of &str
, or something else?
How can I add the needed type annotations onto the []
literal?
Does this depend on the not-yet-stable type ascription feature, or is there a stable way to specify this?
回答1:
One approach that works today is an as
cast specifying both the type and the length:
assert_eq!(a, [] as [&str; 0]);
来源:https://stackoverflow.com/questions/63092178/how-do-i-annotate-the-type-of-an-empty-slice-in-rust