Skip to content

Raw pointer cast triggers "lifetime may not live long enough" #113257

Closed
@ChayimFriedman2

Description

@ChayimFriedman2

I tried this code:

struct Foo<'a>(&'a ());

fn foo(v: *const Foo<'_>) -> *const Foo<'static> {
    v as *const Foo<'static>
}

Playground.

I expected to see this happen: it compiles, since raw pointer casts should be allowed even for completely different types.

Instead, this happened: it fails with:

error: lifetime may not live long enough
 --> src/lib.rs:4:5
  |
3 | fn foo(v: *const Foo<'_>) -> *const Foo<'static> {
  |        - has type `*const Foo<'1>`
4 |     v as *const Foo<'static>
  |     ^^^^^^^^^^^^^^^^^^^^^^^^ type annotation requires that `'1` must outlive `'static`

It looks like for some reason the compiler creates a lifetime obligation here.

Strangely, it works with cast():

fn foo(v: *const Foo<'_>) -> *const Foo<'static> {
    v.cast::<Foo<'static>>()
}

Playground.

Metadata

Metadata

Assignees

Labels

A-coercionsArea: implicit and explicit `expr as Type` coercionsA-raw-pointersArea: raw pointers, MaybeUninit, NonNullC-bugCategory: This is a bug.T-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