如何在Rust中注释空切片的类型? [英] How do I annotate the type of an empty slice in Rust?

查看:115
本文介绍了如何在Rust中注释空切片的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想将Vec<String>与测试中的文字空列表进行比较.

Suppose I want to compare a Vec<String> to a literal empty list in a test.

(我知道实际上我可以检查is_empty(),但是我想了解Rust类型在这里是如何工作的,我认为断言相等将在失败时给出更清晰的信息.)

(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.)

如果我只是说

    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的空白列表?

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]);

这篇关于如何在Rust中注释空切片的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆