1 % Universal Function Call Syntax
3 Sometimes, functions can have the same names. Consider this code:
17 fn f(&self) { println!("Baz’s impl of Foo"); }
21 fn f(&self) { println!("Baz’s impl of Bar"); }
27 If we were to try to call `b.f()`, we’d get an error:
30 error: multiple applicable methods in scope [E0034]
33 note: candidate #1 is defined in an impl of the trait `main::Foo` for the type
35 fn f(&self) { println!("Baz’s impl of Foo"); }
36 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
37 note: candidate #2 is defined in an impl of the trait `main::Bar` for the type
39 fn f(&self) { println!("Baz’s impl of Bar"); }
40 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
44 We need a way to disambiguate which method we need. This feature is called
45 ‘universal function call syntax’, and it looks like this:
56 # fn f(&self) { println!("Baz’s impl of Foo"); }
59 # fn f(&self) { println!("Baz’s impl of Bar"); }
73 These halves of the invocation are the types of the two traits: `Foo` and
74 `Bar`. This is what ends up actually doing the disambiguation between the two:
75 Rust calls the one from the trait name you use.
81 When we call a method like `b.f()` using [method syntax][methodsyntax], Rust
82 will automatically borrow `b` if `f()` takes `&self`. In this case, Rust will
83 not, and so we need to pass an explicit `&b`.
85 [methodsyntax]: method-syntax.html
89 The form of UFCS we just talked about:
95 Is a short-hand. There’s an expanded form of this that’s needed in some
99 <Type as Trait>::method(args);
102 The `<>::` syntax is a means of providing a type hint. The type goes inside
103 the `<>`s. In this case, the type is `Type as Trait`, indicating that we want
104 `Trait`’s version of `method` to be called here. The `as Trait` part is
105 optional if it’s not ambiguous. Same with the angle brackets, hence the
108 Here’s an example of using the longer form.
120 println!("Making a clone of Bar");
122 <Bar as Clone>::clone(self);
127 This will call the `Clone` trait’s `clone()` method, rather than `Foo`’s.