rustHow to compare with null in Rust
Comparing with null
in Rust is done using the Option
enum. Option
is an enum with two variants, Some
and None
. Some
is used to wrap a value, while None
is used to represent the absence of a value.
Example code
let x = Some(5);
let y = None;
match x {
Some(i) => println!("x is {}", i),
None => println!("x is None"),
}
match y {
Some(i) => println!("y is {}", i),
None => println!("y is None"),
}
Output example
x is 5
y is None
Code explanation
let x = Some(5);
: This line declares a variablex
and assigns it the valueSome(5)
.Some
is a variant of theOption
enum, and it wraps the value5
.let y = None;
: This line declares a variabley
and assigns it the valueNone
.None
is a variant of theOption
enum, and it represents the absence of a value.match x {
: This line starts amatch
expression, which is used to compare the value ofx
with the variants of theOption
enum.Some(i) => println!("x is {}", i),
: This line is amatch
arm, and it is used to handle the case wherex
is equal toSome
. The value wrapped bySome
is assigned to the variablei
, and then it is printed.None => println!("x is None"),
: This line is amatch
arm, and it is used to handle the case wherex
is equal toNone
. It prints a message indicating thatx
isNone
.
Helpful links
Related
More of Rust
- How to replace a capture group using Rust regex?
- How to use regex to match a double quote in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to get a capture group using Rust regex?
- How to convert the keys of a Rust HashMap to a vector?
- How to convert Rust bytes to hex?
- How to use non-capturing groups in Rust regex?
- How to use regex with bytes in Rust?
- How to get the last element of a Rust slice?
- How to match the end of a line in a Rust regex?
See more codes...