簡體   English   中英

無法為通用結構實現Into特征

[英]Unable to implement Into trait for a generic struct

我在Rust中為通用結構實現Into特性時遇到了麻煩。 我正在嘗試做的簡化版本如下:

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>塊將T限制為不實現From<Wrapper<T>>

實際上...沒有辦法將其限制為不實現From<Wrapper<T>>類型T Rust沒有“ negative”子句。

通常,實現Into的方法就是簡單地實現From免費獲取Into 但是,在您的情況下,實現將是:

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

這碰到了孤立規則。 不允許對所有T實施From

可能有一個竅門,但我在這里看不到。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM