【发布时间】:2021-06-29 05:51:57
【问题描述】:
我有一个结构:
pub struct Point2D<T>(pub T, pub T);
我希望能够:
- (A) 使用
.into将Point2D<T>转换为(T, T) - (B) 如果
A实现TryInto<B>,则将Point2D<A>和.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