从枚举中读取而不进行模式匹配 [英] Read from an enum without pattern matching

查看:126
本文介绍了从枚举中读取而不进行模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rust 文档提供了此示例,其中名为some_valueResult<T, E>的实例:

The Rust documentation gives this example where we have an instance of Result<T, E> named some_value:

match some_value {
    Ok(value) => println!("got a value: {}", value),
    Err(_) => println!("an error occurred"),
}

有什么方法可以在不进行模式匹配的情况下从some_value进行读取?甚至在运行时不检查内容类型怎么办?也许我们以某种绝对的方式知道所包含的类型,或者也许我们只是一个糟糕的程序员.无论哪种情况,我只是想知道它是否有可能,而不是一个好主意.

Is there any way to read from some_value without pattern matching? What about without even checking the type of the contents at runtime? Perhaps we somehow know with absolute certainty what type is contained or perhaps we're just being a bad programmer. In either case, I'm just curious to know if it's at all possible, not if it's a good idea.

作为一个非常有趣的语言功能,令我印象深刻,以至于很难避免(或不可能?)这个分支.

It strikes me as a really interesting language feature that this branch is so difficult (or impossible?) to avoid.

推荐答案

在最低级别上,不,没有match 1 ,您将无法读取枚举字段.

At the lowest level, no, you can't read enum fields without a match1.

枚举上的方法可以为枚举内的数据提供更方便的访问(例如

Methods on an enum can provide more convenient access to data within the enum (e.g. Result::unwrap), but under the hood, they're always implemented with a match.

如果您知道match中的某个特殊情况是不可访问的,那么通常的做法是编写

If you know that a particular case in a match is unreachable, a common practice is to write unreachable!() on that branch (unreachable!() simply expands to a panic!() with a specific message).

1 如果您的枚举只有一个变体,则还可以编写一个简单的let语句来解构该枚举. letmatch语句中的模式必须是穷举性的,并且匹配枚举中单个变量的模式是穷举性的.但是,只有一种变体的枚举几乎从未使用过.一个结构可以很好地完成这项工作.而且,如果您打算以后添加变体,最好立即编写一个match.

1 If you have an enum with only one variant, you could also write a simple let statement to deconstruct the enum. Patterns in let and match statements must be exhaustive, and pattern matching the single variant from an enum is exhaustive. But enums with only one variant are pretty much never used; a struct would do the job just fine. And if you intend to add variants later, you're better off writing a match right away.

enum Single {
    S(i32),
}

fn main() {
    let a = Single::S(1);
    let Single::S(b) = a;
    println!("{}", b);
}

另一方面,如果您的枚举具有多个变量,则仅对单个变量的数据感兴趣时,也可以使用if letwhile let.虽然letmatch需要穷举模式,但if letwhile let接受非穷举模式.您会经常看到它们与Option一起使用:

On the other hand, if you have an enum with more than one variant, you can also use if let and while let if you're interested in the data from a single variant only. While let and match require exhaustive patterns, if let and while let accept non-exhaustive patterns. You'll often see them used with Option:

fn main() {
    if let Some(x) = std::env::args().len().checked_add(1) {
        println!("{}", x);
    } else {
        println!("too many args :(");
    }
}

这篇关于从枚举中读取而不进行模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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