You need to enable JavaScript to run this app. Rust通用两步From/Into快捷转换实现及类型参数未约束报错解析
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.06 15:54:03