rust-quiz:014-trait-autoref.rs
题目
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")
}
}
}
关键
方法查询
对于T,首先查询T下面的方法,如果找不到,会查找&T的方法。impl
对于impl,不存在所谓的域的作用,只有条件编译。
不论放在哪里,它都会经过编译。
题解
针对第一个match,&0被查出了方法,所以匹配上了true。
这次打印1。
对于第二段match,主要是impl的生效时机。
因为加载并不在于代码所在的域,因此对于char,该方法会返回false。
所以,打印0。
答案
10
本作品采用《CC 协议》,转载必须注明作者和本文链接
关于 LearnKu
推荐文章: