Variance not computed for concrete GAT references in struct fields
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
Similar to https://github.com/rust-lang/rust/issues/114221#issuecomment-1656912412.
I tried this code:
trait Foo {
type Ref<'a>;
}
struct Bar;
impl Foo for Bar {
type Ref<'a> = &'a u8;
}
struct Baz<'a>(<Bar as Foo>::Ref<'a>);
fn f<'a>(s: Baz<'static>) { let _: Baz<'a> = s; }
I expected to see this happen: lifetime check passes
Instead, this happened:
error: lifetime may not live long enough
--> src/main.rs:12:36
|
12 | fn f<'a>(s: Baz<'static>) { let _: Baz<'a> = s; }
| -- lifetime `'a` defined here ^^^^^^^ type annotation requires that `'a` must outlive `'static`
|
= note: requirement occurs because of the type `Baz<'_>`, which makes the generic argument `'_` invariant
= note: the struct `Baz<'a>` is invariant over the parameter `'a`
= help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance
Although lifetime variance does get computed when the GAT type is directly referenced in the parameter type:
fn f<'a>(s: <Bar as Foo>::Ref<'static>) { let _: <Bar as Foo>::Ref<'a> = s; } // check passes
Edit:
Sames limitation on types:
trait Foo {
type GAT<T>;
}
struct Bar;
impl Foo for Bar {
type GAT<T> = T;
}
fn f<'a>(s: <Bar as Foo>::GAT<&'static ()>) { let _: <Bar as Foo>::GAT<&'a ()> = s; } // this passes the check
struct Baz<T>(<Bar as Foo>::GAT<T>);
fn f1<'a>(s: Baz<&'static ()>) { let _: Baz<&'a ()> = s; } // but this doesn't
Meta
rustc --version --verbose:
rustc 1.84.0-nightly (c1db4dc24 2024-10-25)
binary: rustc
commit-hash: c1db4dc24267a707409c9bf2e67cf3c7323975c8
commit-date: 2024-10-25
host: aarch64-apple-darwin
release: 1.84.0-nightly
LLVM version: 19.1.1
Backtrace
<backtrace>
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the two examples with the reported rustc 1.84.0-nightly version, comparing the direct GAT reference with the reference nested in Baz. Trace how variance is computed for concrete GAT references in struct fields; done means the Baz lifetime and type examples pass the same checks as the direct references.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100