Skip to content

Outlives-bounds in type aliases may affect object lifetime defaults which lint type_alias_bounds fails to acknowledge #100270

Closed as not planned
@conradludgate

Description

@conradludgate

I tried this code:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c358b7f20cd1b96bf3919a4339288971

#![allow(dead_code)]

pub type Borrow<'a, T: 'a> = &'a T;

pub trait Foo {
    fn foo(&self);
}

impl<T: AsRef<str> + ?Sized> Foo for T {
    fn foo(&self) {}
}

pub struct Bar<'a> {
    foo: Borrow<'a, dyn Foo>,
}

fn bar(name: &str) {
    let _ = Bar { foo: &name };
}

I expected to see this happen:

error[E0759]: `name` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
  --> src/lib.rs:18:24
   |
17 | fn bar(name: &str) {
   |              ---- this data with an anonymous lifetime `'_`...
18 |     let _ = Bar { foo: &name };
   |                        ^^^^^ ...is used and required to live as long as `'static` here

For more information about this error, try `rustc --explain E0759`.

Borrow<'a, dyn Foo> should default to dyn Foo + 'static and the T: 'a should be ignored.

Instead, this happened:

warning: bounds on generic parameters are not enforced in type aliases
 --> src/lib.rs:3:24
  |
3 | pub type Borrow<'a, T: 'a> = &'a T;
  |                        ^^
  |
  = note: `#[warn(type_alias_bounds)]` on by default
help: the bound will not be checked when the type alias is used, and should be removed
  |
3 - pub type Borrow<'a, T: 'a> = &'a T;
3 + pub type Borrow<'a, T> = &'a T;
  | 

If you follow the guidance from the warning, it no longer compiles due to dyn Foo being static-ish, as mentioned

Metadata

Metadata

Assignees

Labels

A-dyn-traitArea: trait objects, vtable layoutC-bugCategory: This is a bug.L-type_alias_boundsLint: type_alias_boundsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions