Stuck in Rust By Example on pointers/ref

Hi, there's this site

The code that I don't understand is this

fn main() {
    // Assign a reference of type `i32`. The `&` signifies there
    // is a reference being assigned.
    let reference = &4;

    match reference {
        // If `reference` is pattern matched against `&val`, it results
        // in a comparison like:
        // `&i32`
        // `&val`
        // ^ We see that if the matching `&`s are dropped, then the `i32`
        // should be assigned to `val`.
        &val => println!("Got a value via destructuring: {:?}", val),

I don't understand why it is presented. Is it solely for the purpose to show differences between destructuring and dereferencing, or can this code pattern be used in real programs?

When I change &4 to 4 I get a different outcome at compile time, an error, so I can't use that kind of code to do some sort of RTTI. I believe I could do some sort of RTTI by using a cast and None and Some, that is in another example.

So, if that code can only destructure, is it maybe the only way to destructure? Isn't it too long for that?'s "demo code" that demonstrates a difference, but it's impossible to really make use of this code, or is it?

This is presented to show how you destructure references, and nothing more. Rust does not support RTTI beyond using the TypeId/Any trait, but that is a separate topic.

Yes, because &i32 is a different type from i32. They can't be used interchangably.

It is just showing one example of how to destructure references. You can use this pattern in any context that accepts a pattern, like

  • let &x = &4;
  • fn foo(&x: &i32) {. .. }
  • if let &Some(x) = var {}
    • if var: &Option<i32>, then x: i32 in this example
  • etc.
1 Like

Erm...Is there anything that I can add to match reference { &val => val } so that it does something different than just { let &val = reference; val }?

Yes, for example, if you have a reference to a Result,

match result {
    &Ok(x) => (),
    &Err(y) => ()
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.