为包含 Cow<'a, str> 的枚举实现 ToOwned ('a -> 'static) 会导致未满足生命周期要求

Implementing ToOwned ('a -> 'static) for an enum containing Cow<'a, str> causes unmet lifetime requirement

上下文

游乐场link:https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=de1286b8bce0dfb840a5fc0b50df25ad

我正在阅读 ,它说您可以将包含 Cow 的结构转换为具有 'static 生命周期。基于 post,我尝试了以下操作:

use std::borrow::Cow;

enum S<'a> {
    A(Cow<'a, str>),
    B(i32)
}

impl ToOwned for S<'_> {
    type Owned = S<'static>;
    
    fn to_owned(&self) -> Self::Owned {
        match *self {
            S::A(s) => S::A(Cow::Owned(s.clone().into_owned())),
            S::B(i) => S::B(i)
        }
    }
}

fn main() {
    let s = S::A("a".into());
    let s = s.to_owned();
}

并得到以下错误

error: incompatible lifetime on type
   --> src/main.rs:9:18
    |
9   |     type Owned = S<'static>;
    |                  ^^^^^^^^^^
    |
note: because this has an unmet lifetime requirement
note: the lifetime `'_` as defined here...
   --> src/main.rs:8:20
    |
8   | impl ToOwned for S<'_> {
    |                    ^^
note: ...does not necessarily outlive the static lifetime introduced by the compatible `impl`

问题

TL;DR: 你不能为此实现 ToOwned;使用固有方法。


ToOwned::Owned 有界:

type Owned: Borrow<Self>;

所以我们需要 S<'static> 来为任何 'a.

实现 Borrow<S<'a>>

...除了不能写这个 impl:

error[E0119]: conflicting implementations of trait `std::borrow::Borrow<S<'static>>` for type `S<'static>`
  --> src/main.rs:19:1
   |
19 | impl<'a> Borrow<S<'a>> for S<'static> {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: conflicting implementation in crate `core`:
           - impl<T> Borrow<T> for T
             where T: ?Sized;

...因为它与一揽子实施冲突 Borrow<T> for T 其中 'a'static.

没有这个impl的编译器错误是编译器看到一个impl<'a> Borrow<S<'a>> for S<'static>(上述一揽子实现)这一事实的结果,它只是它限制了 'a: 'static。因此编译器试图证明 'a: 'static,但失败了。这是编译器 over-smart 导致混淆错误消息的示例。