False positive "lifetime may not live long enough" with Cow, ToOwned and Sized · Issue #108345 · rust-lang/rust (original) (raw)

I tried this code:

use std::borrow::Cow;

pub trait Trait { fn method(self) -> Cow<'static, str> where Self: Sized; }

impl Trait for Cow<'_, str> { fn method(self) -> Cow<'static, str> where Self: Sized, { Cow::<'static, str>::Borrowed("") } }

I expected to see this happen: it compiles.

Instead, this happened: lifetime may not live long enough

If I remove the where Self: Sized in both trait declaration and implementation, it compiles. However, in real world application, there are other methods in this trait so I have to add where Self: Sized to make the trait dyn-safe.

If I remove the where Self: Sized only in implementation, it compiles. However, If the return type is changed to Option<Cow<'static, str>>, the code would warn about impl method assumes more implied bounds than the corresponding trait method. I think this might be a bug.

use std::borrow::Cow;

pub trait Trait { fn method(self) -> Option<Cow<'static, str>> where Self: Sized; }

impl Trait for Cow<'_, str> { fn method(self) -> Option<Cow<'static, str>> { None } }

Meta

rustc --version --verbose:

rustc 1.67.1 (d5a82bbd2 2023-02-07)
binary: rustc
commit-hash: d5a82bbd26e1ad8b7401f6a718a9c57c96905483
commit-date: 2023-02-07
host: aarch64-apple-darwin
release: 1.67.1
LLVM version: 15.0.6

Backtrace

error: lifetime may not live long enough
  --> src/main.rs:14:9
   |
10 |     fn method(self) -> Cow<'static, str>
   |               ---- has type `Cow<'1, str>`
...
14 |         Cow::<'static, str>::Borrowed("")
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ proving this value is `Sized` requires that `'1` must outlive `'static`

error: could not compile `my-test-2` due to previous error