How do I pass an enum variant to match on as a function parameter?

浪子不回头ぞ 提交于 2020-01-14 03:36:14

问题


I would like to pass in the parameters what arm of the enum I need to match, something like this:

enum D {
    A(i64),
    B(u64),
    C(u64, u64),
}
let a = D.A(10);
println!(a.is_of(D.A)); // true
println!(a.is_of(D.B)); // false

I know I can use matching rules for this, but I'd like this is_of method to take as an input of the enum options for my purposes.


回答1:


You cannot.

  • It is not possible to pass types as function parameters.
  • Enum variants are not types to start with.

If you are OK using a macro instead of a function, see

  • How do I assert an enum is a specific variant if I don't care about its fields?
  • The matches crate

See also:

  • Compare enums only by variant, not value

  • Can traits be used on enum types?

  • Can struct-like enums be used as types?
  • Is there a way to use existing structs as enum variants?


来源:https://stackoverflow.com/questions/57171185/how-do-i-pass-an-enum-variant-to-match-on-as-a-function-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!