Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

rust pattern matching for String field

  1. User

    rust pattern matching for String field

  2. Assistant

    In Rust, you can use pattern matching to match on a String field using the match expression. 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 Person struct with a name field of type String. We use pattern matching in the match expression to match on the name field.

    The ref s pattern allows us to bind a reference to the String field to the s variable. We then compare s with 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.