【问题标题】:Implementing Into when possible and using TryInto otherwise尽可能实现 Into,否则使用 TryInto
【发布时间】:2021-06-29 05:51:57
【问题描述】:

我有一个结构:

pub struct Point2D<T>(pub T, pub T);

我希望能够:

  • (A) 使用.intoPoint2D&lt;T&gt; 转换为(T, T)
  • (B) 如果A 实现TryInto&lt;B&gt;,则将Point2D&lt;A&gt;.tryInto 转换为(B, B)

我可以实现(A):

impl<T> std::convert::Into<(T, T)> for Point2D<T> {
    fn into(self) -> (T, T) {
        (self.0, self.1)
    }
}

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

    #[test]
    fn into() {
        let a: Point2D<u32> = Point2D(42, 42);
        let a_into :(u32, u32) = a.into();
        let b: (u32, u32) = (42, 42);
        assert_eq!(a_into, b);
    }
}

我可以实现(B):

#[derive(Debug)]
pub enum PointIntoError<T> {
    ErrorInX(T),
    ErrorInY(T),
}

impl<FromType, ToType> TryInto<(ToType, ToType)> for Point2D<FromType>
    where FromType: TryInto<ToType>,
          FromType: Copy {
    type Error = PointIntoError<FromType>;

    fn try_into(self) -> Result<(ToType, ToType), Self::Error> {
        let x_ = self.0.try_into();
        let y_ = self.0.try_into();

        match x_ {
            Ok(x) => {
                match y_ {
                    Ok(y) => Ok((x, y)),
                    _ => Result::Err(PointIntoError::ErrorInY(self.1))
                }
            }
            _ => Result::Err(PointIntoError::ErrorInX(self.0))
        }
    }
}

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

    #[test]
    fn try_into() {
        let a: Point2D<u32> = Point2D(400, 400);
        let a_into :(u16, u16) = a.try_into().expect("Could not convert to tuple of u16");
        let b: (u16, u16) = (400, 400);
        assert_eq!(a_into, b);
    }

    #[test]
    #[should_panic]
    fn try_into_fail() {
        let a: Point2D<u32> = Point2D(400, 400);
        let a_into :(u8, u8) = a.try_into().expect("Could not convert to tuple of u8");
    }
}

单独运行时,两个测试都通过了。但是,当我尝试编译 impls 时,我得到:

error[E0119]: conflicting implementations of trait `std::convert::TryInto<(_, _)>` for type `Point2D<_>`:
  --> src/lib.rs:31:1
   |
31 | / impl<FromType, ToType> TryInto<(ToType, ToType)> for Point2D<FromType>
32 | |     where FromType: TryInto<ToType>,
33 | |           FromType: Copy {
34 | |     type Error = PointIntoError<FromType>;
...  |
49 | |     }
50 | | }
   | |_^
   |
   = note: conflicting implementation in crate `core`:
           - impl<T, U> std::convert::TryInto<U> for T
             where U: TryFrom<T>;

error: aborting due to previous error

For more information about this error, try `rustc --explain E0119`.

该错误并不是特别有用,但我猜对于实现Into 的结构,TryInto 有某种默认实现,因此我不能同时定义两者。

在有意义的情况下同时支持Into 转换和TryInto 转换的最惯用方式是什么?我想我总是可以.tryInto.expect 当我确定类型匹配但看起来不整洁时。

【问题讨论】:

  • 也欢迎代码质量和其他反馈;我还是 Rust 的新手

标签: generics rust type-conversion traits idioms


【解决方案1】:

我猜对于实现 Into 的结构的 TryInto 有某种默认实现,因此我不能同时定义两者。

这是正确的,更具体地说,对于实现 Into 的任何结构,都有一个全面实现 TryFrom(对于实现 From 的任何结构,它都是一揽子实现):https://doc.rust-lang.org/std/convert/trait.TryFrom.html#impl-TryFrom%3CU%3E

在有意义的情况下支持 Into 转换和 TryInto 转换的最惯用方式是什么?我想我总是可以 .tryInto 和 .expect 当我确定类型匹配但它看起来并不整洁时。

我认为最惯用的方法是将您的 Into 实现转换为普通方法,例如.into_tuple(),这是一个相当常见的模式,例如slice::into_vecString::into_boxed_str

【讨论】:

    猜你喜欢
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 2021-04-08
    • 1970-01-01
    相关资源
    最近更新 更多