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 variablexand assigns it the valueSome(5).Someis a variant of theOptionenum, and it wraps the value5.let y = None;: This line declares a variableyand assigns it the valueNone.Noneis a variant of theOptionenum, and it represents the absence of a value.match x {: This line starts amatchexpression, which is used to compare the value ofxwith the variants of theOptionenum.Some(i) => println!("x is {}", i),: This line is amatcharm, and it is used to handle the case wherexis equal toSome. The value wrapped bySomeis assigned to the variablei, and then it is printed.None => println!("x is None"),: This line is amatcharm, and it is used to handle the case wherexis equal toNone. It prints a message indicating thatxisNone.
Helpful links
Related
More of Rust
- How to match whitespace with a regex in Rust?
- How to replace strings using Rust regex?
- Regex example to match multiline string in Rust?
- How to use regex lookbehind in Rust?
- How to use regex lookahead in Rust?
- How to use Unicode in a regex in Rust?
- How to increment pointer in Rust
- How to split a string with Rust regex?
- How to create a Rust regex from a string?
- Rust HashMap example
See more codes...