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 match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to match a URL with a regex in Rust?
- How to get an entry from a HashSet in Rust?
- How to clear a Rust HashMap?
- How to convert a vector to a Rust slice?
- How to replace all matches using Rust regex?
- How to get a capture group using Rust regex?
- How to use regex to match a double quote in Rust?
- How to convert the keys of a Rust HashMap to a vector?
See more codes...