-
-
Notifications
You must be signed in to change notification settings - Fork 57
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Question 14: auto-ref in trait method call
- Loading branch information
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
Answer: 10 | ||
Difficulty: 1 | ||
|
||
# Hint | ||
|
||
Trait method auto-ref is covered in [this excellent Stack Overflow answer][SO]. | ||
|
||
[SO]: https://stackoverflow.com/a/28552082/6086311 | ||
|
||
# Explanation | ||
|
||
Trait impls anywhere in a program are always in scope, so there is no | ||
significance to the `impl Trait for char` being written inside of a block of | ||
code. In particular, that impl is visible throughout the whole program, not just | ||
within the block containing the impl. | ||
|
||
This question relates to the behavior of trait method auto-ref which is covered | ||
in [this Stack Overflow answer][SO]. | ||
|
||
[SO]: https://stackoverflow.com/a/28552082/6086311 | ||
|
||
The call to `0.is_reference()` observes that there is no implementation of | ||
`Trait` for an integer type that we could call directly. Method resolution | ||
inserts an auto-ref, effectively evaluating `(&0).is_reference()`. This time the | ||
call matches `impl<'a, T> Trait for &'a T` and prints `1`. | ||
|
||
The call to `'?'.is_reference()` instead finds `impl Trait for char`, printing | ||
`0`. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
trait Trait: Sized { | ||
fn is_reference(self) -> bool; | ||
} | ||
|
||
impl<'a, T> Trait for &'a T { | ||
fn is_reference(self) -> bool { | ||
true | ||
} | ||
} | ||
|
||
fn main() { | ||
match 0.is_reference() { | ||
true => print!("1"), | ||
false => print!("0"), | ||
} | ||
|
||
match '?'.is_reference() { | ||
true => print!("1"), | ||
false => { | ||
impl Trait for char { | ||
fn is_reference(self) -> bool { | ||
false | ||
} | ||
} | ||
print!("0") | ||
} | ||
} | ||
} |