Search code examples
rustreferencedestructuring

How to destructure and derefence tuple in rust


Is there a way to simplify the below code by dereferencing foo and bar on the same line as we destructure the tuple?

let a = "a";
let b = "b";
let c = (&a, &b);

// Can we dereference here?
let (foo, bar) = c;

let foo_loc = *foo;
let bar_loc = *bar;
println!("{}", foo_loc);
println!("{}", bar_loc);

Solution

  • You can pattern match the references:

    fn main() {
        let a = "a";
        let b = "b";
        let c = (&a, &b);
        let (&foo, &bar) = c;
        println!("{}", foo);
        println!("{}", bar);
    }
    

    Playground