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 variablexof typeOption<i32>and assigns it the valueSome(5).match x {: This line starts amatchexpression, 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 theSomevariant of theOptiontype. If this pattern matches, the codeprintln!("x is {}", i)is executed, whereiis the value wrapped in theSomevariant.None => println!("x is None"): This line is a pattern that matches theNonevariant of theOptiontype. If this pattern matches, the codeprintln!("x is None")is executed.
Helpful links
Related
More of Rust
- How to use binary regex in Rust?
- How to use regex captures in Rust?
- How to perform matrix operations in Rust?
- How to use regex to match a double quote in Rust?
- How to yield a thread in Rust?
- How to print a Rust HashMap?
- How to match whitespace with a regex in Rust?
- How to add an entry to a Rust HashMap?
- How to extend a Rust HashMap?
- How to replace a capture group using Rust regex?
See more codes...