]> git.proxmox.com Git - rustc.git/blame - src/doc/rust-by-example/src/trait/disambiguating.md
New upstream version 1.63.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / trait / disambiguating.md
CommitLineData
e1599b0c
XL
1# Disambiguating overlapping traits
2
923072b8
FG
3A type can implement many different traits. What if two traits both require
4the same name? For example, many traits might have a method named `get()`.
5They might even have different return types!
e1599b0c 6
923072b8
FG
7Good news: because each trait implementation gets its own `impl` block, it's
8clear which trait's `get` method you're implementing.
e1599b0c
XL
9
10What about when it comes time to _call_ those methods? To disambiguate between
11them, we have to use Fully Qualified Syntax.
12
13```rust,editable
14trait UsernameWidget {
15 // Get the selected username out of this widget
16 fn get(&self) -> String;
17}
18
19trait AgeWidget {
20 // Get the selected age out of this widget
21 fn get(&self) -> u8;
22}
23
24// A form with both a UsernameWidget and an AgeWidget
25struct Form {
26 username: String,
27 age: u8,
28}
29
30impl UsernameWidget for Form {
31 fn get(&self) -> String {
32 self.username.clone()
33 }
34}
35
36impl AgeWidget for Form {
37 fn get(&self) -> u8 {
38 self.age
39 }
40}
41
42fn main() {
923072b8 43 let form = Form {
e1599b0c
XL
44 username: "rustacean".to_owned(),
45 age: 28,
46 };
47
923072b8 48 // If you uncomment this line, you'll get an error saying
e1599b0c
XL
49 // "multiple `get` found". Because, after all, there are multiple methods
50 // named `get`.
51 // println!("{}", form.get());
52
53 let username = <Form as UsernameWidget>::get(&form);
54 assert_eq!("rustacean".to_owned(), username);
55 let age = <Form as AgeWidget>::get(&form);
56 assert_eq!(28, age);
57}
58```
59
60### See also:
61
62[The Rust Programming Language chapter on Fully Qualified syntax][trpl_fqsyntax]
63
64[trpl_fqsyntax]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name