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