How does this match syntax work?

#1

I’m new to Rust. Although I’ve finished the book without much problem, I often see syntax that is bizzare.

In this example, I was doing some online exercise. I haven’t seen syntax like this (originally it didn’t have the & before Some() and failed to compile),

let robot_name = &Some(String::from(“Bors”));

but I figure it is equivalent to

let x = Some();
let robot_name = &x;

but then how does match works it out by matching a Some() to a &Some()? At first I thought it was deref coercion, but when I add another & to the Some(name) inside match, it failed.

fn main() {
let robot_name = &Some(String::from("Bors"));

match robot_name {
    Some(name) => println!("Found a name: {}", name),
    None => (),
}

println!("robot_name is: {:?}", robot_name);

}

playground

#2
1 Like
#3

In the first bit of code:

let robot_name = &Some(String::from(“Bors”));

//but I figure it is equivalent to

let x = Some();
let robot_name = &x;

Some is actually an enum variant for Option, and not a function, and therefore Some(value) is actually the constructor for the Some variant. Not to mention that we don’t have function parameter overloading (yet) in rust, so even if it were a function it wouldn’t’ve worked.
The reason your code below works is because the Option is now a &Option (When you declare &Some(Value)), meaning that your match arm becomes

Some(ref name) => {/**/}

because the actual value (Within the &Option) is at some point behind a reference, so you can only take it by reference in your match arm, therefore making it

Some(ref name) => {/**/}

Because there’s no possibility that you’d want to move out of borrowed content.