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?