![[Rust Guide] 6.4. Simple Control Flow - If Let](/_next/image?url=https%3A%2F%2Fmedia2.dev.to%2Fdynamic%2Fimage%2Fwidth%3D1200%2Cheight%3D627%2Cfit%3Dcover%2Cgravity%3Dauto%2Cformat%3Dauto%2Fhttps%253A%252F%252Fdev-to-uploads.s3.amazonaws.com%252Fuploads%252Farticles%252F48d3w3h6mdsd6hhz2uqj.png&w=1200&q=75)
[Rust Guide] 6.4. Simple Control Flow - If Let
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



