Confused & symbol

Pls look at this code

fn parse_version(header: &[u8]) -> Result<i32, &'static str> {
    match header.get(0) {
        None => Err("invalid header length"),
        Some(&1) => {
            println!("this is 1");
            Ok(1)
        },
        Some(&2) => {
            println!("this is 2");
            Ok(2)
        }
        Some(_) => Err("invalid version"),
    }
}

fn main() {
    let version = parse_version(&[1, 2, 3, 4]);
    match version {
        Ok(v) => println!("working with version: {v:?}"),
        Err(e) => println!("error parsing header: {e:?}"),
    }
}

It works, however

fn parse_version(header: &[u8]) -> Result<i32, &'static str> {
    match header.get(0) {
        None => Err("invalid header length"),
        Some(1) => {
            println!("this is 1");
            Ok(1)
        },
        Some(2) => {
            println!("this is 2");
            Ok(2)
        }
        Some(_) => Err("invalid version"),
    }
}

fn main() {
    let version = parse_version(&[1, 2, 3, 4]);
    match version {
        Ok(v) => println!("working with version: {v:?}"),
        Err(e) => println!("error parsing header: {e:?}"),
    }
}

It alse works !

I am confused that Whether the & is essential here?

This is called match ergonomics, and basically the compiler is dereferencing the value for you.

As for why you can return a value that is behind a reference, it's because u8 implements the Copy trait, therefore the compiler is simply copying every value in order for parse_version to work as is.

Why this code not work?

fn parse_version() {
    let s = Some("michaelma".to_string());
    match s {
        Some(&s_v) => println!("this is 1"),
        None => println!("this is 2"),
    }
}

fn main() {
    parse_version();
}

Some(s_v) or Some(ref s_v) works, however Some(&s_v) doesn't

Match ergonomics will automatically add an implicit &, it won't remove a superfluous & as in your last example.

Match ergonomics rules are one of the most confusing parts of Rust.

I can't agree with you more :disappointed_relieved:

The reference is incomplete, to boot.

Here's a recentish attempt at an explanation (with some citations).