Rust Lang

Rust if let

The if let expression in rust allows you to match an expression to a specific pattern. This is different from the if expression that runs when a condition is true.

Using the let keyword, you can specify a pattern that is compared against the specified expression. If the expression matches the pattern, we execute the if block; otherwise, run the else block.

Let us explore how to use them if let expression in Rust.

If Let

We can express the syntax for the if let construct as shown below:

iflet patter = expr {
    // run me
} else {
    //  run met
}

Consider the example below that illustrates how to use them if let expression in Rust:

fnmain() {
letdb = "MySQL";
iflet"MySQL" = db {
println!("You need a schema!")
    } elseiflet"MongoDB" = db {
println!("You do not need a schema!");
    }
}

In the example above, we have a variable db that holds the string “MySQL”. We then use the if let expression to check for a specific pattern.

If the value is “MySQL”, we execute the block inside the if let block. Otherwise, run the else if let block.

Running the code above should return:

If we change the value of the db variable to “MongoDB”. We can get the result as shown:

let db = "MongoDB";

The output is as shown:

We can also define a condition for all non-matching patterns using the else block. An example is as shown:

fnmain() {
letdb = "Unknown";
iflet"MySQL" = db {
println!("You need a schema!")
    } elseiflet"MongoDB" = db {
println!("You do not need a schema!");
    } else {
println!("Unknown database paradigm!")
    }
}

In the above example, the value of the db variable is “Unknown”. Since a blocking matches that pattern, the other block is executed.

We can use the if let block to assign a value to a variable. An example is as shown below:

letdb = iftrue {
"MySQL"
  }else {
"MongoDB"
    };
println!("Db is {}: ", db);

If the value is true, set the variable to “MySQL”; else, set the value to “MongoDB”. The returning value is shown:

Ending

This guide explores the fundamentals of using the if let expression in Rust. The if let expression allows us to specify a code block if an expression matches a specified pattern.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list