Rust通用两步From/Into快捷转换实现及类型参数未约束报错解析
Rust 通用类型转换实现的相关问题
需求说明
StructA 实现了 From<StructB>,且 StructB 实现了 From<S>,希望能够通用实现快捷转换 Into<StructA> for S 或 From<S> for StructA。
如果这是不合理的设计思路也请告知,但仍希望为了学习目的说明具体实现方式。
尝试的实现代码
struct StructA { f: StructB } struct StructB { g: i32 } impl From<StructB> for StructA { fn from(v: StructB) -> Self { Self { f: v } } } impl From<i32> for StructB { fn from(v: i32) -> Self { Self { g: v } } } impl<T: Into<StructA>, S: Into<T>> Into<StructA> for S { fn into(self) -> StructA { let i: T = self.into(); i.into() } }
编译报错与疑惑
运行上述代码时收到报错:the type parameter 'T' is not constrained by the impl trait, self type, or predicates
无法理解该报错的原因:T 不是已经被 Into<StructA> 约束了吗?
内容的提问来源于stack exchange,提问作者wisha
相关产品推荐
相关产品推荐

