[英]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.