gpt4 book ai didi

rust - 如何解决 "upstream crates may add a new impl of trait"错误?

转载 作者:行者123 更新时间:2023-12-03 11:25:01 29 4
gpt4 key购买 nike

我创建了一个特性,用于从某些值转换为我需要的类型。该转换已包含在 From 中/Into适用于多种类型,但不是我想要的所有类型。我以为我可以利用这一点,但很快就得到了一个错误“上游 crate 可能会添加一个新的特征实现”。
( playground 中的精简示例)

pub trait Cookable {
fn cook(self) -> (String, Vec<i8>);
}

impl<T: Into<Vec<i8>>> Cookable for T {
fn cook(self) -> (String, Vec<i8>) {
(String::from("simple"), self.into())
}
}

impl Cookable for &str {
fn cook(self) -> (String, Vec<i8>) {
(String::from("smelly"), vec![self.len()])
}
}
这会触发以下错误:
error[E0119]: conflicting implementations of trait `Cookable` for type `&str`:
--> src/lib.rs:11:1
|
5 | impl<T: Into<Vec<i8>>> Cookable for T {
| ------------------------------------- first implementation here
...
11 | impl Cookable for &str {
| ^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `&str`
|
= note: upstream crates may add a new impl of trait `std::convert::From<&str>` for type `std::vec::Vec<i8>` in future versions
我担心解决此错误的唯一方法是为已经具有 Into 的每个类型指定单独的特征实现。 .

最佳答案

这不是您可以“解决”的问题。这是编译器强加的限制,以防止将来对依赖项的更改巧妙地更改代码的行为。
现在,您通过实现具体类型而不是使用泛型和特征来避免错误。宏是减少必须执行的键盘输入量的一种方法。
将来,某种形式的特化也可能有助于解决这个问题。然而,这恰好是特化不稳定的原因。可以使用这种类型的特化仅使用安全代码来创建不健全的 Rust。正在研究一种简化形式的特化,但它故意避开基于特征的特化能力,仅适用于具体类型。
也可以看看:

  • Resolving trait implementation conflicts
  • Conflicting implementations of trait in Rust
  • How can I implement From for both concrete Error types and Box<Error> in Rust?
  • How is there a conflicting implementation of `From` when using a generic type?
  • I implemented a trait for another trait but cannot call methods from both traits
  • 关于rust - 如何解决 "upstream crates may add a new impl of trait"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63136970/

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