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

余生颓废 提交于 2020-08-07 07:54:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!