Skip to content

Commit ada9843

Browse files
committed
Correct UFCS example using Foos and Bars
1 parent 3053f49 commit ada9843

File tree

1 file changed

+33
-11
lines changed

1 file changed

+33
-11
lines changed

src/expressions.md

+33-11
Original file line numberDiff line numberDiff line change
@@ -550,32 +550,54 @@ let pi: Result<f32, _> = "3.14".parse();
550550
Function calls may sometimes result in ambiguities about receiver or referent.
551551
See [UFCS](#unambiguous-function-call-syntax) for how to resolve this.
552552

553-
### Unambiguous Function Call Syntax
553+
### Unambiguous Function Call Syntax (UFCS)
554554

555555
Several situations often occur which result in ambiguities about the receiver or
556556
referent of method or associated function calls. These situations may include:
557557

558558
* Multiple in-scope traits define the same method for the same types
559559
* Auto-`deref` is undesirable; for example, distinguishing between methods on a
560-
smart pointer itself and the pointer's referent.
561-
* Methods which take no arguments and return properties of a type, like
562-
`SizeOf::size_of()`
560+
smart pointer itself and the pointer's referent
561+
* Methods which take no arguments, like `default()`, and return properties of a
562+
type, like `size_of()`
563563

564564
The programmer may unambiguously refer to their desired method or function using
565565
Unambiguous Function Call Syntax (UFCS), specifying only as much type and path
566566
information as necessary.
567567

568568
For example,
569569

570-
```rust,ignore
571-
// shorthand, only if `T` is a path
572-
T::size_of()
570+
```rust
571+
trait Foo {
572+
fn quux();
573+
}
574+
575+
trait Bar {
576+
fn quux();
577+
}
578+
579+
struct Faz;
580+
impl Foo for Faz {
581+
fn quux() {}
582+
}
583+
584+
struct Baz;
585+
impl Foo for Baz {
586+
fn quux() {}
587+
}
588+
impl Bar for Baz {
589+
fn quux() {}
590+
}
591+
592+
fn main() {
593+
// shorthand, only if unambiguous
594+
Faz::quux();
573595

574-
// infer trait `SizeOf` based on traits in scope.
575-
<T>::size_of()
596+
// Baz::quux(); // Error: multiple `quux` found
576597

577-
// completely unambiguous; works if multiple in-scope traits define `size_of()`
578-
<T as SizeOf>::size_of()
598+
// completely unambiguous; works if multiple in-scope traits define `quux`
599+
<Baz as Foo>::quux();
600+
}
579601
```
580602

581603
Refer to [RFC 132] for further details, motivations, and subtleties of syntax.

0 commit comments

Comments
 (0)