if let

There are Options and Results in Rust. Depending on the function called, these types wrap real values that are to be handled by the program. There are match and if let statements to handle those.

I pretty much understand match statements, because they kind of resembled switch statements in JavaScript. The if let statements were the ones that kind of confused me. They kind of confused me, because I was thinking they had to do something with variable declarations upon conditionals. Otherwise, why would there be an if and a let in the statement?

Then I finally came across a brilliant use case for them. I ended up using if let statements a lot in one of my hobby programs. This use case helped me to understand them so much more.

1
2
3
if let Some(url) = element.value().attr("href") {
  //... handle url
}

The previous code essentially says that the option Some(url) value that comes from element.value().attr("href") method will be handled within the curly braces.

An if let statement is just the syntax way to handle one match statement without requiring the erroror default handler. So the syntax could turn out to be much shorter than using a match statement.