Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Enum hierarchy through reflection #198

Unanswered
danielopitz asked this question in Q&A
Discussion options

I wonder, is it possible to get names / values of enums given an enum hierarchy?

use facet::{Facet, Peek};
#[derive(Facet)]
#[repr(u8)]
enum A {
 EA(B),
}
#[derive(Facet)]
#[repr(u8)]
enum B {
 EB(C),
}
#[derive(Facet)]
#[repr(u8)]
enum C {
 EC
}
let x = A::EA(B::EB(C::EC)));
let peek = Peek::new(&x);
match peek {
 Peek::Enum(pe) => {
 let variant = pe.active_variant();
 println!("{}", variant.name);
 // how do I descdend further? I would like to get a vec in the end: ["A::EA", "B::EB", "C::EC"]
 }
}
You must be logged in to vote

Replies: 2 comments 3 replies

Comment options

Things are going to change in Facet Reflect, but you're looking for variant.fields which in turn has its own def.

You must be logged in to vote
2 replies
Comment options

Thanks a lot for the swift response! I can descend now in the hierarchy and see all of the variants of each enum, but is it possible to know which enum variant is selected?

Sorry if the questions are dumb, I'm quite the beginner in the Rust world and sometimes it's rather easy to miss things. Reflection works a little bit different in the programming languages I know, this doesn't make it easier!

Don't want to waste your time as well!

Comment options

Here's the example I'm playing with:

use facet::Facet;
use facet_reflect::Peek;
#[derive(Facet)]
#[repr(u8)]
enum D {
 VD1,
 VD2,
 VD3,
}
#[derive(Facet)]
#[repr(u8)]
enum C {
 VC1,
}
#[derive(Facet)]
#[repr(u8)]
enum B {
 VB1(C),
 VB2(D),
}
#[derive(Facet)]
#[repr(u8)]
enum A {
 VA1(B),
}
fn main() {
 let e = A::VA1(B::VB2(D::VD3));
 let p = Peek::new(&e);
 match p {
 Peek::Enum(pe) => {
 let variant = pe.active_variant();
 println!("{}", variant.name);
 match variant.kind {
 facet::VariantKind::Tuple { fields } => {
 for field in fields {
 let d = field.shape.def;
 println!("{:?}", d);
 }
 }
 _ => todo!(),
 }
 }
 _ => todo!(),
 }
}
Comment options

(See #188 for the facet-reflect changes — I'm sorry for the API churn, I'm trying to merge it as fast as I can to avoid a lot of people contributing on the old API. )

You must be logged in to vote
1 reply
Comment options

Thank you for the heads up! I don't mind API changes at all, will update when necessary! The library is <1.0.0 and it's a hard / difficult task as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
✋ question Further information is requested

AltStyle によって変換されたページ (->オリジナル) /