Back to articles
[Rust Guide] 6.4. Simple Control Flow - If Let
How-ToTools

[Rust Guide] 6.4. Simple Control Flow - If Let

via Dev.toSomeB1oody

6.4.1. What Is if let ? The if let syntax allows if and let to be combined into a less verbose way to handle a value that matches one pattern while ignoring the rest of the patterns . You can think of if let as syntactic sugar for match , meaning it lets you write code for just one specific pattern. 6.4.2. Practical Use of if let For example, v is a u8 variable. Determine whether v is 0 , and print zero if it is. use rand :: Rng ; // Use an external crate fn main (){ let v : u8 = rand :: thread_rng () .gen_range ( 0 ..= 255 ); // Generate a random number println! ( "{}" , v ); match v { 0 => println! ( "zero" ), _ => (), } } Here we only need to distinguish between 0 and non- 0 . In this case, using if let is even simpler: fn main (){ let v : u8 = rand :: thread_rng () .gen_range ( 0 ..= 255 ); // Generate a random number println! ( "{}" , v ); if let 0 = v { println! ( "zero" ); }; } Note: if let uses = rather than == . Let’s make a small change to the example above: v is a u8 variabl

Continue reading on Dev.to

Opens in a new tab

Read Full Article
4 views

Related Articles