[rust-dev] ref binding for parameters of functions?

Sebastian Gesemann s.gesemann at gmail.com
Wed Jul 2 10:04:29 PDT 2014

On Wed, Jul 2, 2014 at 6:21 PM, Alex Crichton wrote:
> Binding by ref is subtly different that the function still owns the
> argument. For example, this may go awry with "ref:T"
> struct Foo;
> impl Drop for Foo {
>     fn drop(&mut self) { println!("dropping"); }
> }
> fn foo(ref _param: Foo) {}
> fn main() {
>     let f1: fn(ref:Foo) = foo;
>     let f2: fn(Foo) = foo;
>     let f3: fn(&Foo) = foo;
>     f1(Foo);
>     f2(Foo);
>     f3(&Foo);
> }
> In that program, how many times is `dropping` printed? It should be
> three,

This program would not compile. Here's why: If one wanted `foo`'s
`_param` to refer to the caller's memory -- a behaviour one *might*
expect because that's how `ref` works in other contexts, specifically,
it does not create a temporary and then a reference it -- this would
make the first parameter of `foo` effectivly a reference to `Foo`, not
a value of `Foo`. The only difference between ref:T and &T in a
function signature would be that ref:T implies auto-referencing at the
call site where &T does not. The function pointers would be compatible
because the implementation of foo just works on a reference in both
cases. The line

    let f2: fn(Foo) = foo;

however, tries to assign the adress of a function taking a reference
to Foo to a pointer for functions that take a value of Foo. This would
be a type error.


More information about the Rust-dev mailing list