Skip to content

anonymous constants are overly restrictive wrt variance #90629

Closed
@lcnr

Description

@lcnr

cc #89829 (comment)

this currently causes an error as 'a is considered invariant because it is used in an anonymous constant.

#![feature(generic_const_exprs)]
struct Foo<'a>([&'a u32; std::mem::size_of::<&'a u32>()]);
fn covariant<'a>(v: &'a Foo<'static>) -> &'a Foo<'a> {
    v //~ERROR mismatched types
}

This shouldn't actually be needed for std::mem::size_of as it doesn't care about variance.

Once stuff like the following causes an error (instead of a future imcompat lint, cc #56105), subtyping should not be able to influence const eval, so we could allow lifetimes used in constants to remain bivariant. It is not clear that we should do that, as this restriction on subtyping is definitely not obvious or even necessarily desirable.

trait SadBee {
    const ASSOC: usize;
}
// fn(&'static ())` is a supertype of `for<'a> fn(&'a ())` while
// we allow two different impls for these types, leading
// to different const eval results.
impl SadBee for for<'a> fn(&'a ()) {
    const ASSOC: usize = 0;
}
impl SadBee for fn(&'static ()) {
    const ASSOC: usize = 100;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-genericsArea: const generics (parameters and arguments)A-varianceArea: Variance (https://doc.rust-lang.org/nomicon/subtyping.html)C-bugCategory: This is a bug.F-generic_const_exprs`#![feature(generic_const_exprs)]`

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions