Const generics: get a value of certain type by enum value

I have an enum type and some structs, I want to use const generic to get a struct value depends on what enum valule is:

struct SFoo {}

struct SBar {}

enum E {
    Foo = 0,
    Bar = 1,
}

fn get<const E : i32>() -> T {
    // if E == E::Foo as _  return SFoo {}
    // if E == E::Bar as _  return SBar {}
}

Any ideas?

P.S. macros, unstable features are Okay, as long as the API won't change.

I think that would be a bad idea because:

  • const generics likely isn't developed enough for this
  • it's not possible to return a generic parameter that hasn't been declared as one. The fn doesn't know what T is.
  • the choice of what to substitute for type params cannot be made at runtime. Therefore, you might as well just use a match expr instead of a fn. Using a fn this way is potentially confusing.
  • even if all the issues above were solved, you'd get a fn that returns a value of a type, not a fn that returns a type.
2 Likes

About the last point, I do want a value, I updated my question.

I asked a silly question. SFoo and SBar are types of my own, I shoud make them as structs with const generics:

struct S<const E: i32> {}

enum E {
    Foo = 0,
    Bar = 1,
}

impl E {}

fn get<const E: i32>() -> S<{ E }> {
    S::<{ E }> {}
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.