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?
We use the if statement when we need to check for only one condition. If the condition is true, perform a specific action. We start with the if keyword followed by an expression that evaluates a Boolean value. If the expression evaluates to be true, then execute the code inside the curly braces.
Declaring a variable In Rust, we can create variables by assigning data to alphanumeric words( excluding keywords) using the let keyword or const keyword. Syntax: let x = "Value"; or const x = "Value"; Example: Rust.
Rust has two kinds of statement: declaration statements and expression statements.
Keyword letBind a value to a variable. The primary use for the let keyword is in let statements, which are used to introduce a new set of variables into the current scope, as given by a pattern.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With