#match statement

16 messages · Page 1 of 1 (latest)

tulip gyro
#

you have 2 cases: empty string, and everything else that gets put in the ceo variable

#

so you exhaust all posibilities of a string

#

ceo => .. is a _ => .. with a name

#

matches always work on constant values

#

you need an if if you want to compare it to another var

#

yes

#

the only confusing exception is that you can have named consts in match that act like a literal

#
    const X: &str = "abc";
    let ceo = match ceo {
        "" => None,
        X => panic!(""),```
#

X is "abc" in this case

#

not a var

#

it is shadowing

#
impl Company {
    fn new(name: &str, ceo_1: &str) -> Self {
        let ceo_3 = match ceo_1 {
            "" => None,
            ceo_2 => Some(ceo_2.to_string()),
        };                                             
        Self {
            name: name.to_string(),
            ceo: ceo_3,
        }
    }
}```
#

that's what the compiler sees

#

unlike in C++, the right side of the assignment can't see the variable declared on the left side

#

you just gave me an exam question with that shadowing xD

split bramble
#

The ceo in the match is a variable binding shadowing the outer CEO. This code is equivalent:

let ceo = match ceo {
    "" => None,
    other => Some(other.to_string()),
};```or
```rs
let ceo = match ceo {
    "" => None,
    other => {
        let ceo = other;
        Some(ceo.to_string()) // this is in reference to the local ceo binding, not from the outer fn
    },
};```