Skip to content

Commit

Permalink
Question 14: auto-ref in trait method call
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Nov 28, 2018
1 parent 326877a commit 05e70f7
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
28 changes: 28 additions & 0 deletions questions/014-trait-autoref.md
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`.
28 changes: 28 additions & 0 deletions questions/014-trait-autoref.rs
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")
}
}
}

0 comments on commit 05e70f7

Please sign in to comment.