Options - Rust Programming
Автор: Code Bits
Загружено: 2023-08-14
Просмотров: 514
Описание:
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
Повторяем попытку...
Доступные форматы для скачивания:
Скачать видео
-
Информация по загрузке: