0

The first of the two below example match blocks compiles, the second does not. Why?

fn main() {

    let string1 = String::from("string1");
    let string2 = String::from("string2");
    
    let test_string = String::from("string1");

    match test_string {

        string1 => {
            println!("{}", string1);
        },

        string2 => {
            println!("{}", string2);
        },

        _ => {
            println!("Not {} or {}", string1, string2);
        }

    }
    
    match test_string {
        
        String::from("string1") => {
            println!("string1");
        },
        
        String::from("string2") => {
            println!("string2");
        },
        
        _ => {
            println!("Not string1 or string2");
        }
        
    }
    
}

Associated error:

expected tuple struct or tuple variant, found associated function `String::from

What type is returned by String::from? I thought this should be a String. According to the documentation here, I am not totally sure which function is called.

https://doc.rust-lang.org/std/convert/trait.From.html#tymethod.from

FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225
  • 1
    The first code compiles but gives warnings, and will not do what you expect (`string1` and `string2` are match variables that match anything). – interjay May 16 '23 at 13:43

0 Answers0