Skip to content

Associated type lifetime bounds are underconstrained #22246

Closed
@aturon

Description

The following code:

use std::ops::Deref;

pub trait ToOwned {
    type Owned: Borrow<Self>;
    fn to_owned(&self) -> Self::Owned;
}

pub enum Cow<'a, B: ?Sized + 'a> where B: ToOwned {
    Borrowed(&'a B),
    Owned(<B as ToOwned>::Owned)
}

impl<'a, B: ?Sized> Deref for Cow<'a, B> where B: ToOwned {
    type Target = B;

    fn deref(&self) -> &B {
        match *self {
            Cow::Borrowed(borrowed) => borrowed,
            Cow::Owned(ref owned) => owned.borrow()
        }
    }
}

pub trait Borrow<Borrowed: ?Sized> {
    fn borrow(&self) -> &Borrowed;
}

fails with:

<anon>:19:24: 19:33 error: the associated type `<B as ToOwned>::Owned` may not live long enough [E0311]
<anon>:19             Cow::Owned(ref owned) => owned.borrow()
                                 ^~~~~~~~~
<anon>:19:24: 19:33 help: consider adding an explicit lifetime bound for `<B as ToOwned>::Owned`
<anon>:19             Cow::Owned(ref owned) => owned.borrow()
                                 ^~~~~~~~~
<anon>:16:27: 21:6 note: the associated type `<B as ToOwned>::Owned` must be valid for the anonymous lifetime #1 defined on the block at 16:26...
<anon>:16     fn deref(&self) -> &B {
<anon>:17         match *self {
<anon>:18             Cow::Borrowed(borrowed) => borrowed,
<anon>:19             Cow::Owned(ref owned) => owned.borrow()
<anon>:20         }
<anon>:21     }
<anon>:19:24: 19:33 note: ...so that the reference type `&<B as ToOwned>::Owned` does not outlive the data it points at
<anon>:19             Cow::Owned(ref owned) => owned.borrow()

The same code not using associated types does not have this problem.

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions