The code we are looking at here is bloated. In Rust, you often use the MATCH command, which is quite potent, it ensures all scenarios have been accounted for. there are times when a lighter touch is needed. Sometimes, grabbing a bit of data from an enumeration and proceeding forward is enough.
The chunk of code in front of us is overkill. It's filled with unnecessary code comments that obscure the main point: we just want to snag the relevant data within a variable, only choosing to print if there is data to print. We're seeing a super-efficient solution here, the Rust "if let" command.
MATCH can be a bit awkward in cases, leading to staggering amounts of code and indentation. The Rust example here is much more straightforward, it comprises three lines of code, including the closing syntax bracket. It does the same job, but much more efficiently.
The if let command can intelligently snag available data or choose to do nothing. It’s more manageable and readable, essential when you want easily understandable code. Although if statements and variable bindings are familiar to me, the approach Rust gives us here was unusual but very clean.
We've initialized a number as an enumeration with the value of seven in the code. Consider the situation where we have an enumeration with three variants. The last variant, 'quix,' is associated with a 32-bit unsigned integer data type.
We have defined a variable 'c,' which is an instance of the 'quix' variant with a value of 100. In the if let construct, we try to match 'c' with the 'quix' variant and assign the associated value to 'v.' We can then print 'v.' In a separate if let construct, we use the at (@) symbol to match 'c' with 'quix' and assign the associated value to 'v,' but only if 'v' is within the range 0-100. In this way, Rust provides a syntax for capturing both the compared part and extra data in an if let construct.
Sometimes things can get a little more complicated, like when you want to check whether a value falls within a specific range. That's when you have to bring in nested if let constructs. Still, the ability to include range checks right within the if let construct is quite powerful.
The trick is to extend the match arm syntax from only exact equality 'if let Variant(data) = value' to also allow range inclusion 'if let Variant(0..=100 @ data) = value.' This brings even more conciseness and readability, and it's good to know if you need to read such patterns in code.
Ещё видео!