rustHow to check a value for null in Rust
To check a value for null in Rust, you can use the Option
type. Option
is an enum with two variants: Some
and None
. Some
is used to wrap a value, while None
is used to indicate the absence of a value.
Example code
let x: Option<i32> = Some(5);
match x {
Some(i) => println!("x is {}", i),
None => println!("x is None"),
}
Output example
x is 5
Code explanation
let x: Option<i32> = Some(5);
: This line declares a variablex
of typeOption<i32>
and assigns it the valueSome(5)
.match x {
: This line starts amatch
expression, which is used to compare a value against a list of patterns and execute code based on which pattern matches.Some(i) => println!("x is {}", i)
: This line is a pattern that matches theSome
variant of theOption
type. If this pattern matches, the codeprintln!("x is {}", i)
is executed, wherei
is the value wrapped in theSome
variant.None => println!("x is None")
: This line is a pattern that matches theNone
variant of theOption
type. If this pattern matches, the codeprintln!("x is None")
is executed.
Helpful links
Related
More of Rust
- How to replace strings using Rust regex?
- How to convert a Rust HashMap to a BTreeMap?
- How to get a capture group using Rust regex?
- How do I identify unused variables in Rust?
- How to parse JSON string in Rust?
- How to convert a Rust HashMap to JSON?
- How to replace a capture group using Rust regex?
- Hashshet example in Rust
- How to use non-capturing groups in Rust regex?
- How to match the end of a line in a Rust regex?
See more codes...