Generics 在可能的情况下实施到,否则使用TryInto
我有一个结构:Generics 在可能的情况下实施到,否则使用TryInto,generics,rust,type-conversion,traits,idioms,Generics,Rust,Type Conversion,Traits,Idioms,我有一个结构: pub结构点2d(pub T,pub T); 我希望能够: (A) 使用将点2D转换为(T,T) (B) 如果a实现了tryInto 我可以实施(A): impl std::convert::Into for Point2D{ fn进入(自我)->(T,T){ (self.0,self.1) } } #[cfg(测试)] 模试验{ 使用超级::*; #[测试] fn到(){ 设a:Point2D=Point2D(42,42); 让a_进入:(u32,u32)=a.进入();
pub结构点2d(pub T,pub T);
我希望能够:
- (A) 使用
将
转换为点2D
(T,T)
- (B) 如果
实现了a
tryInto
impl std::convert::Into for Point2D{
fn进入(自我)->(T,T){
(self.0,self.1)
}
}
#[cfg(测试)]
模试验{
使用超级::*;
#[测试]
fn到(){
设a:Point2D=Point2D(42,42);
让a_进入:(u32,u32)=a.进入();
设b:(u32,u32)=(42,42);
断言eq!(a到b);
}
}
我可以实施(B):
#[派生(调试)]
发布枚举点输入错误{
ErrorInX(T),
误差(T),
}
点2D的impl TryInto
其中FromType:TryInto,
FromType:复制{
类型错误=PointIntoError;
fn尝试(自我)->结果{
让x_u=self.0.尝试进入();
让y=self.0.尝试进入();
匹配x_{
Ok(x)=>{
匹配y_{
Ok(y)=>Ok((x,y)),
_=>结果::Err(pointintorer::ErrorInY(self.1))
}
}
_=>结果::Err(pointintorer::ErrorInX(self.0))
}
}
}
#[cfg(测试)]
模试验{
使用超级::*;
#[测试]
fn try_into(){
设a:Point2D=Point2D(400400);
让a_-into:(u16,u16)=a.try_-into().expect(“无法转换为u16的元组”);
设b:(u16,u16)=(400400);
断言eq!(a到b);
}
#[测试]
#[应该恐慌]
fn尝试失败(){
设a:Point2D=Point2D(400400);
设a_-into:(u8,u8)=a.try_-into().expect(“无法转换为u8的元组”);
}
}
单独运行时,两个测试都通过。但是,当我尝试编译这两个impl
s时,我得到:
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`.
error[E0119]:类型`Point2D`的trait`std::convert::TryInto`的实现冲突:
-->src/lib.rs:31:1
|
31 |/impl TryInto用于Point2D
32 | |其中FromType:TryInto,
33 | | FromType:复制{
34 | |类型错误=PointIntoError;
... |
49 | | }
50 | | }
| |_^
|
=注意:板条箱“核心”中的实现冲突:
-impl std::convert::TryInto for T
其中U:TryFrom;
错误:由于上一个错误而中止
有关此错误的详细信息,请尝试“rustc--explain E0119”。
这个错误并不是特别有用,但我猜对于将实现为的结构,TryInto
有某种默认实现,因此我不能同时定义这两种
在有意义的情况下,支持转换为和TryInto
转换的最惯用方法是什么?我想我总是可以.tryInto
和.expect
当我确定类型匹配但看起来不整洁时
我猜对于实现到的结构,TryInto有某种默认实现,因此我不能同时定义这两种
这是正确的,更具体地说,对于实现到的任何结构,都有一个TryFrom
的整体实现(对于实现From
的任何结构,都是整体实现的):
在有意义的情况下,支持转换和尝试转换的最惯用方式是什么?我想我总是可以。尝试和。期待当我确定类型匹配,但它似乎不整洁
我认为最惯用的方法是将转化为实现,转化为普通方法,例如。转化为tuple()
,这是一种相当常见的模式,例如slice::Into_vec
或String::Into_boxed_str
,代码质量和其他欢迎反馈;我还是个新手