Options - Rust Programming

Published: 14 August 2023
on channel: Code Bits
296
11

In rust, Option is an enum with two variants. It can either have some value, or be None. It is used to represent the presence or absence of a value.

Using Option
This division function will return None if denominator is 0.
Otherwise it will return the value wrapped in Some.

Unwrapping
You cannot straight away use an option, you must handle it. You can use unwrap to get the value, but it will panic if the option is None.

Unwrap-or
```rust
let result = divide(4.0, 0.0).unwrap_or(-1.0);
println!("{result}"); // -1.0.
```
You can safely unwrap by using unwrap or method. This will return the default value if the option is None.

Match
A safe way to handle options is to use match. However, this syntax is not commonly used


If-Let
Instead, we can use if let syntax. This is a shorthand for match. It is more concise and readable

#rustlang #coding


On this page of the site you can watch the video online Options - Rust Programming with a duration of hours minute second in good quality, which was uploaded by the user Code Bits 14 August 2023, share the link with friends and acquaintances, this video has already been watched 296 times on youtube and it was liked by 11 viewers. Enjoy your viewing!