Borrow operator in match arms

Hi. I'm teaching myself Rust from the book and experimenting a little as I go. I'm quite familiar with basic general imperative and functional programming concepts but I have very little practical programming experience.

In the code example below I'm confused as why I have to use a borrow operator (&) in the match arm Some(&first) => first, from the first match block but not in Some(sixth) => println!("The sixth element is: {}", sixth), from the second match block.

Does it have somethign to do with the fact that I'm assigning the result of the match to something in the first case, and not in the second?

Or is it to do with the println! macro automatically dereferencing?

Or am I barking up the wrong tree entirely?

I would greatly appreciate if someone could help to explain, please? Thanks :slight_smile:

    let mut v: Vec<i32> = vec![1, 2, 3, 4, 5];

    let first: i32 = match v.get(0) {
        Some(&first) => first,
        None => 0,
    };

    println!("The first element is: {}", first);

    v.push(6);

    match v.get(5) {
        Some(sixth) => println!("The sixth element is: {}", sixth),
        None => println!("There is no sixth element."),
    }

Almost. println! does not automatically dereference. Rather, Display (the trait used when you format with "{}") is implemented for references to be equivalent to formatting the referent.

1 Like

Rather, Display (the trait used when you format with "{}" ) is implemented for references to be equivalent to formatting the referent.

Excellent, thanks. I know very little about traits so far, but surpisingly, this explanation does make sense!

When you do get to writing your own traits, keep in mind that including such implementations for references when it makes sense may be worthwhile; they often solve problems in generic code.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.