【问题标题】:How to fix "warning: unused variable" for enum with named params in Rust?如何在 Rust 中使用命名参数修复枚举的“警告:未使用的变量”?
【发布时间】:2017-01-15 21:36:55
【问题描述】:

我有一个像这样的枚举:

pub enum Tag<'a> {
    Container { c: Vec<Tag<'a>> },
    // ...
}

当我尝试匹配时:

impl<'a> Display for Tag<'a> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match *self {
            Tag::Container { ref c } => write!(f, "{}", "container"),
            // ...
        }
    }
}

我明白了:

warning: unused variable: `c`, #[warn(unused_variables)] on by default
   |
65 |             Tag::Container{ref c} => write!(f, "{}", "container"),

在其他一些地方。

我尝试使用_,只是为了删除ref c,但这都会导致错误。

【问题讨论】:

    标签: enums rust warnings


    【解决方案1】:

    你可以使用..:

    match *self {
        Tag::Container { .. } => write!(f, "{}", "container"),
    

    这在本书中有介绍,特别是在Ignoring bindings 下,它用于忽略封装在枚举变体中的值:

    enum OptionalTuple {
        Value(i32, i32, i32),
        Missing,
    }
    
    let x = OptionalTuple::Value(5, -2, 3);
    
    match x {
        OptionalTuple::Value(..) => println!("Got a tuple!"),
        OptionalTuple::Missing => println!("No such luck."),
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-21
      • 1970-01-01
      • 2013-12-15
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      相关资源
      最近更新 更多