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 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!