gpt4 book ai didi

generics - 无法为通用结构实现 Into 特征

转载 作者:行者123 更新时间:2023-11-29 08:06:23 26 4
gpt4 key购买 nike

我在执行 Into 时遇到问题Rust 中通用结构的特征。下面是我正在尝试做的简化版本:

struct Wrapper<T> {
value: T
}

impl<T> Into<T> for Wrapper<T> {
fn into(self) -> T {
self.value
}
}

当我尝试编译时,出现以下错误:

error: conflicting implementations of trait `std::convert::Into<_>` for type `Wrapper<_>`: [--explain E0119]
--> <anon>:5:1
|>
5 |> impl<T> Into<T> for Wrapper<T> {
|> ^
note: conflicting implementation in crate `core`

我的印象是问题出在标准库中的以下实现:

impl<T, U> Into<T> for U where T: From<U>

T 可能实现From<Wrapper<T>> ,这可能是一个冲突的实现。有什么办法可以解决这个问题吗?例如,有没有办法让 impl<T> block 限制 T到不实现 From<Wrapper<T>> 的类型?

最佳答案

实际上...没有办法将其限制为类型 T未实现 From<Wrapper<T>> . Rust 没有“否定”子句。

通常情况下,实现方式Into就是简单地实现From得到 Into 免费。但是,在您的情况下,实现将是:

impl<T> From<Wrapper<T>> for T {
fn from(w: Wrapper<T>) -> T { w.value }
}

这就违反了孤儿规则。不允许执行 From对于所有 T .

可能有一个技巧,但我在这里看不到。

关于generics - 无法为通用结构实现 Into 特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39186652/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com