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 replace a capture group using Rust regex?
- How to match whitespace with a regex in Rust?
- How to match a URL with a regex in Rust?
- How to use regex captures in Rust?
- How to push an element to a Rust slice?
- How to clone struct in Rust
- How to get a capture group using Rust regex?
- How to replace all matches using Rust regex?
- How to replace strings using Rust regex?
- How to use non-capturing groups in Rust regex?
See more codes...