gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
rust pattern matching for String field
- User
rust pattern matching for String field
- Assistant
In Rust, you can use pattern matching to match on a
Stringfield using thematchexpression. Here's an example:struct Person { name: String, } fn main() { let person = Person { name: String::from("John"), }; match person.name { // match a specific value ref s if s == "John" => { println!("The person's name is John"); } // match any other value _ => { println!("The person's name is not John"); } } }In this example, we have a
Personstruct with anamefield of typeString. We use pattern matching in thematchexpression to match on thenamefield.The
ref spattern allows us to bind a reference to theStringfield to thesvariable. We then compareswith the value we're looking for ("John") and if it matches, we execute the corresponding code block.The
_pattern is a wildcard pattern that matches any value. If the name doesn't match "John", the code in the_block will be executed.