< 返回版块

minstrel1977 发表于 2021-11-01 23:15

Tags:2021版次,rust-analyzer

pub struct GreaterThanZero(i32);

impl TryFrom<i32> for GreaterThanZero {
    type Error = &'static str;

    fn try_from(value: i32) -> Result<Self, Self::Error> {        
        Ok(GreaterThanZero(value))
    }
}

pub trait MyTrait {
    // This has the same name as `TryInto::try_into`
    fn try_into(&self) -> Result<GreaterThanZero, ()>;
}

impl MyTrait for i32 {
    fn try_into(&self) -> Result<GreaterThanZero, ()> {
        Ok(GreaterThanZero(*self + 1))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn internal() {
        let a: &dyn MyTrait = &2;
        let v: GreaterThanZero = (&*a).try_into().unwrap();
        assert_eq!(3,v.0);
    }
}

这段代码能测试通过,所以这里的try_into应该是应用了MyTrait下的,但是vscode中的rust-analyzer提示是core::convert::TryInto中的try_into得到了执行。

评论区

写评论
johnmave126 2021-11-02 01:29

改成

pub trait MyTrait {
    // This has the same name as `TryInto::try_into`
    fn try_into(&self, addition: i32) -> Result<GreaterThanZero, ()>;
}

impl MyTrait for i32 {
    fn try_into(&self, addition: i32) -> Result<GreaterThanZero, ()> {
        Ok(GreaterThanZero(*self + addition))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn internal() {
        let a: &dyn MyTrait = &2;
        let v: GreaterThanZero = (&*a).try_into(1).unwrap();
        assert_eq!(3, v.0);
    }
}

这样RA甚至会报mismatched-arg-count的错,跟rust-analyzer#10673应该是同一个bug

1 共 1 条评论, 1 页