HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustMajor

Idiomatic way of assigning a value from an if else condition in Rust

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
idiomaticconditionfromelsewayrustvalueassigning

Problem

What is the preferred way of creating or assigning one of several objects to variables inside an "if - else" construct in Rust? Because of the scoping, it seems the variable must be created outside the if - else. Neither of the ways I've thought of seem very nice. Using strings as an example, here's one way, but it generates a warning about an unused assignment:

let mut s = String::new();
if condition {
    s = "first".to_string();
} else {
    s = "second".to_string();
}


Another alternative is this:

let mut s = "second".to_string();
if condition {
    s = "first".to_string();
}


It's shorter and doesn't generate a warning, but means s is being assigned twice, and means that "second".to_string() runs but is wasted if condition is true. If instead of simple string creation these were expensive operations (perhaps with side effects) this method wouldn't be suitable.

Is there a better alternative?

Solution

In Rust, an if/else block is an expression. That is to say, the block itself has a value, equivalent to the last expression in whatever section was executed. With that in mind, I would structure your code like this:

let s = if condition {
    "first"
} else {
    "second"
}.to_string();

Code Snippets

let s = if condition {
    "first"
} else {
    "second"
}.to_string();

Context

Stack Overflow Q#53981783, score: 97

Revisions (0)

No revisions yet.