[英]How to cascading implement Into trait for struct?
我正在尝试为结构实现一些转换特征,以避免不必要的 into() 混乱。 这是我正在尝试的:
struct TypeA {}
struct TypeB {}
impl Into<TypeA> for TypeB {
fn into(self) -> TypeA { unimplemented!(); }
}
impl<T: Into<TypeB>> Into<TypeA> for T {
fn into(self) -> TypeA {
unimplemented! ();
}
}
struct TypeC {}
impl Into<TypeB> for TypeC {
fn into(self) -> TypeB { unimplemented!(); }
}
但是编译器抛出以下错误
conflicting implementations of trait `std::convert::Into<TypeA>`
= note: conflicting implementation in crate `core`:
- impl<T, U> Into<U> for T
where U: From<T>;
那么,如何为任何实现 Into<TypeB> 的类型实现 trait Into<TypeA>? TypeA、TypeB 和 TypeC 都在本地 crate 中。
我只需要弄清楚转换错误。 对于TypeA
,我在Into<TypeB>
上实现了From
。 这允许任何可以转换Into<TypeB>
的东西转换Into<TypeA>
。 最后一个测试从TypeC
转换为TypeA
。
struct TypeA {
name: String,
}
struct TypeB {
name: String,
}
struct TypeC {
name: String,
}
impl From<TypeC> for TypeB {
fn from(c: TypeC) -> Self {
TypeB { name: c.name }
}
}
impl<T: Into<TypeB>> From<T> for TypeA {
fn from(b: T) -> Self {
let b = b.into();
TypeA { name: b.name }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn c_to_b() {
let c = TypeC {
name: "C".to_string(),
};
let b: TypeB = c.into();
assert_eq!("C", b.name.as_str())
}
#[test]
fn b_to_a() {
let b = TypeB {
name: "B".to_string(),
};
let a: TypeA = b.into();
assert_eq!("B", a.name.as_str())
}
#[test]
fn c_to_a() {
let c = TypeC {
name: "C".to_string(),
};
let a: TypeA = c.into();
assert_eq!("C", a.name.as_str())
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.