When would grammar `fn foo(&v: &A)` be used?

#1

Just out of curiosity, not problem I met.

As my understanding, the type signature means foo takes a reference to A as input. But &v pattern undoes it, so foo's parameter is actually passed by value.

When would this useage be necessary to use?

#2

If you need to implement a trait that takes inputs by reference, but you want to use the inputs by value.

Note that this only works for Copy types

trait Trait<T> {
    fn by_ref(t: &T);
}

impl Trait<i32> for () {
    fn by_ref(&t: &i32) {
        do_work(t)
    }
}

fn do_work(_: i32) {}
1 Like
#3

So this “usage” does not take ownership?

#4

No, but with Copy types ownership doesn’t really matter anyways. Every time they move, you still get to use the old value.

1 Like