< 返回版块

xiaoyaou 发表于 2025-12-10 18:02

Tags:泛型,方法调用

pub fn main() {
    let x: &mut i32 = &mut 0;

    // 不能自动重借用`&mut T` 为 `&T`
    // let failed: My         = x.into0();
    let manually_reborrow: My = (&*x).into0();
    let auto_reborrow: My     = x.into1();
}

struct My;

impl<'a> From<&'a i32> for My {
    fn from(_: &'a i32) -> Self {
        My
    }
}

trait MyInto0<U> {
    fn into0(self) -> U;
}

impl<T, U: From<T>> MyInto0<U> for T {
    fn into0(self) -> U {
        From::from(self)
    }
}

trait MyInto1<U> {
    fn into1(self) -> U;
}

impl<'a, U: From<&'a i32>> MyInto1<U> for &'a i32 {
    fn into1(self) -> U {
        From::from(self)
    }
}

评论区

写评论

还没有评论

1 共 0 条评论, 1 页