rustHow do I use a variable in a match statement in Rust?
Using a variable in a match statement in Rust is a powerful way to control the flow of your program. The match statement is a powerful tool for pattern matching and allows you to compare a variable to a set of patterns.
Example code
let x = 5;
match x {
1 => println!("x is 1"),
2 => println!("x is 2"),
3 => println!("x is 3"),
4 => println!("x is 4"),
5 => println!("x is 5"),
_ => println!("x is something else"),
}
Output example
x is 5
Code explanation
let x = 5;
- This declares a variablex
and assigns it the value5
.match x {
- This begins the match statement and uses the variablex
as the value to be matched.1 => println!("x is 1"),
- This is a pattern that matches the value1
and prints the stringx is 1
if the value ofx
is1
._ => println!("x is something else"),
- This is a catch-all pattern that matches any value that is not matched by the other patterns and prints the stringx is something else
.
Helpful links
Related
- How do I write a variable to a file in Rust?
- How do I access a tuple variable by index in Rust?
- How do I print the type of a variable in Rust?
- How do I use a variable number of arguments in Rust?
- How do I print a variable in Rust?
- How do I add padding to a variable in Rust?
- How can I use a mutex as a global variable in Rust?
- How can I use a hashmap as a global variable in Rust?
- How do I declare a variable without initializing it in Rust?
- How do I identify unused variables in Rust?
More of Rust
- Bitwise operator example in Rust
- How to use regex lookahead in Rust?
- How to match the end of a line in a Rust regex?
- How to use look behind in regex in Rust?
- How to use regex with bytes in Rust?
- How to use regex to match a double quote in Rust?
- How to perform matrix operations in Rust?
- How to replace a capture group using Rust regex?
- How to calculate the inverse of a matrix in Rust?
- How to parse JSON string in Rust?
See more codes...