Ref and & for function arguments

here is a small example to show the differences

// Crate a non copy type to make the move error visible
#[derive(Debug)]
struct NoCopy;

#[derive(Debug)]
struct Foo(NoCopy);

// this takes Foo by ref but it tries to take ownership of the inner value
// with we can't do since Foo is borrowed and the value can't be copied.
// fn test(&Foo(val): &Foo) {}

// here we take a ref to Foo and take a ref to it's inner value
fn test_ref(&Foo(ref val): &Foo) {
    println!("val: {:?}", val)
}

fn main() {
    let foo = &Foo(NoCopy);
    test_ref(foo);
}

edit: btw we don't need to make the destruction in the function header we can also do it in the body like this:

fn test_ref(foo: &Foo) {
    let &Foo(ref val) = foo;
    println!("val: {:?}", val)
}
1 Like