Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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?

like image 461
Bob Avatar asked Dec 30 '18 22:12

Bob


People also ask

How do you use if statements in Rust?

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.

How do you give a variable a type in Rust?

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.

Is rust a statement?

Rust has two kinds of statement: declaration statements and expression statements.

What is let rust?

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.


1 Answers

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(); 
like image 186
Benjamin Lindley Avatar answered Sep 26 '22 10:09

Benjamin Lindley