Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I annotate the type of an empty slice in Rust? [duplicate]

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?

like image 436
poolie Avatar asked Jul 25 '20 18:07

poolie


1 Answers

One approach that works today is an as cast specifying both the type and the length:

assert_eq!(a, [] as [&str; 0]);
like image 145
poolie Avatar answered Nov 16 '22 04:11

poolie