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?
One approach that works today is an as
cast specifying both the type and the length:
assert_eq!(a, [] as [&str; 0]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With