Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

rust - How do I access a variable outside of an `if let` expression?

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...