Skip to content

Mismatched assumptions for interaction between associated type and lifetime in trait #24622

Closed
@huonw

Description

@huonw
pub trait Foo<'a> {
    type Bar: std::fmt::Debug;
    fn baz(&'a self) -> Self::Bar;
}

pub struct X {
    name : String,
}

impl<'a> Foo<'a> for X {
    type Bar = &'a String;
    fn baz(&'a self) -> &'a String {
        &self.name
    }
}

pub fn foo<T: for<'a> Foo<'a>>(x: T) {
    let y = x.baz();
    drop(x);
    // for T = X, this is a &String pointing to dropped memory
    println!("{:?}", y); 
}

pub fn main() {
    foo(X { name: "foo".to_string() });
}

This segfaults.

The impl is allowing &'a String because 'a is in scope, but the use in foo assumes that Bar is independent of 'a.

(Noticed in http://stackoverflow.com/q/29745134/1256624 .)

Metadata

Metadata

Assignees

Labels

A-associated-itemsArea: Associated items (types, constants & functions)A-lifetimesArea: Lifetimes / regionsA-trait-systemArea: Trait systemP-highHigh priorityT-langRelevant to the language team

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions