Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why qualified path patterns accept constants, structs and enum variants even though the reference forbid those?

Path patterns are patterns that refer either to constant values or to structs or enum variants that have no fields.

Unqualified path patterns can refer to:

enum variants, structs, constants, associated constants

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Qualified path patterns can only refer to associated constants.

source

I created this example for this:

mod m {
    pub mod n {
        pub const CONST: i32 = 1;
        pub struct S;
        pub enum E {
            V,
        }

        pub struct A;

        impl A {
            pub const ASSOC_CONST: i32 = 2;
        }
    }
}

fn main() {
    let v = 10;

    match v {
        m::n::CONST => (),
        m::n::A::ASSOC_CONST => (),
        _ => (),
    }

    let v = m::n::S {};

    match v {
        m::n::S {} => (),
    }

    let v = m::n::E::V;

    match v {
        m::n::E::V => (),
    }
}

And it compiles without an issue even though I use qualified path patterns. Shouldn’t this fail for anything but associated constants in the example?

>Solution :

Qualified paths are paths like <T as Trait>::CONSTANT and can only refer to trait-associated items, which are functions, types, and constants. The only one of those that can be used in patterns is constants.

All your paths are unqualified/simple.

Here’s one that attempts to use a qualified path:

struct A;
struct B(i32);

trait HasType {
    type T;
}

impl HasType for A {
    type T = B;
}

fn main() {
    let b = B(5);
    let <A as HasType>::T(n) = b;
    println!("{n}");
}

It produces these errors:

error[E0575]: expected method or associated constant, found associated type `HasType::T`
  --> src/main.rs:14:9
   |
14 |     let <A as HasType>::T(n) = b;
   |         ^^^^^^^^^^^^^^^^^
   |
   = note: can't use a type alias as a constructor

error[E0658]: usage of qualified paths in this context is experimental
  --> src/main.rs:14:9
   |
14 |     let <A as HasType>::T(n) = b;
   |         ^^^^^^^^^^^^^^^^^
   |
   = note: see issue #86935 <https://github.com/rust-lang/rust/issues/86935> for more information

The linked issue is Tracking Issue for "More Qualified Paths" #86935.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading