Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Main difference between if and if-let in Rust

Tags:

rust

I don't see the reason why we use if let and just usual if. In Rust book, chapter 6.3, the sample code is below:

let some_u8_value = Some(0u8);
if let Some(3) = some_u8_value {
    println!("three");
}

The code above is same with:

let some_u8_value = Some(0u8);
if Some(3) == some_u8_value {
    println!("three");
}

Any other reason on why we would use if let or what is it specifically for?

like image 248
Yosi Pramajaya Avatar asked Jan 11 '20 07:01

Yosi Pramajaya


People also ask

What does if let do in Rust?

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.

Does rust have else if?

In this Rust tutorial we learn how to control the flow of our Rust application with if, else if, else, and match conditional statements. We also cover how to nest conditional statements inside other conditional statements as well as how to conditionally assign a value to a variable if the if let expression.

What is ref in Rust?

ref annotates pattern bindings to make them borrow rather than move. It is not a part of the pattern as far as matching is concerned: it does not affect whether a value is matched, only how it is matched.

What does some mean in Rust?

Rust doesn't have null , but if you want to talk about a value that may not exist, you use Option<WhateverTypeThatValueIs> . When it does exist, it will be a Some(value) , else None . Example: let x: Option<u32> = Some(2); assert_eq!(


1 Answers

Another reason is if you wish to use the pattern bindings. For example consider an enum:

enum Choices {
  A,
  B,
  C(i32),
}

If you wish to implement specific logic for the C variant of Choices, you can use the if-let expression:

let choices: Choices = ...;

if let Choices::C(value) = choices {
    println!("{}", value * 2);
}
like image 105
sshashank124 Avatar answered Oct 18 '22 19:10

sshashank124