如何访问 `if let` 表达式之外的变量? [英] How do I access a variable outside of an `if let` expression?

查看:45
本文介绍了如何访问 `if let` 表达式之外的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问命令行参数.如果论证存在,就做点什么,如果不存在,就什么都不做.我有这个代码:

I'm trying to access command line arguments. If the argument exists, do something, if not, do nothing. I have this code:

fn main() {
    if let Some(a) = std::env::args().nth(2) {
        let b = a;
    }

    println!("{}", a);
}

我无法在此范围之外访问 ab:

I am not able to access a or b outside of this scope:

error[E0425]: cannot find value `a` in this scope
 --> src/main.rs:6:20
  |
6 |     println!("{}", a);
  |                    ^ not found in this scope

我该如何解决这个问题?有没有更好的方法来处理我正在尝试做的事情?

How do I resolve this? Is there a better way to approach what I'm trying to do?

推荐答案

要了解正在发生的事情,请查看 theShepmaster 的回答

For an understanding of what's going on, have a look at the answer by Shepmaster

如果不满足条件,我不确定您希望发生什么.如果你只是想在这种情况下中止程序,惯用的 Rust 方法是使用 unwrapexpect.

I'm not sure what you expect to happen in case the condition is not met. If you just want to abort the program in that case, the idiomatic Rust way is to use unwrap or expect.

// panics if there are fewer than 3 arguments.
let a = env::args().nth(2).unwrap();

println!("{}", a);

如果你想要一个默认值以防参数不存在,你可以使用 unwrap_or.

If you want a default value in case the argument does not exist, you can use unwrap_or.

// assigns "I like Rust" to a if there are fewer than 3 arguments
let a = env::args().nth(2).unwrap_or("I like Rust".to_string());

println!("{}", a);

作为进一步的选择,您可以使用在 Rust 中几乎所有东西都是表达式的特性:

As a further alternative, you can use the feature that in Rust almost everything is an expression:

let b = if let Some(a) = env::args().nth(2) {
    a
} else {
    // compute alternative value
    let val = "some value".to_string();
    // do operations on val
    val
};
println!("{}", b);

惯用的 Rust 编写方式是使用闭包和 unwrap_or_else:

The idiomatic Rust way to write that would be with closures and unwrap_or_else:

let b = env::args().nth(2).unwrap_or_else(|| {
    // compute alternative value
    let val = "some value".to_string();
    // do operations on val
    val
});
println!("{}", b);

这篇关于如何访问 `if let` 表达式之外的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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