Can I extend an enum with additional values?

An enum can’t be directly extended, but you use the same composition trick one would use with structs (that is, with a struct, one would have a field storing an instance of the ‘parent’). enum Base { Alpha, Beta(usize), } enum Extended { Base(Base), Gamma } If you wish to handle each case individually, this … Read more

How to manage serialize / deserialize an enum property with Dart / Flutter to Firestore?

Flutter is able to generate JSON serialization code. The tutorial you can find here. It references the package json_annotation. It contains also support for enum serialization. So all you need, is use this tool and annotate your enum values with @JsonValue. From the code docs: An annotation used to specify how a enum value is … Read more

How in Swift specify type constraint to be enum?

enum SomeEnum: Int { case One, Two, Three } class SomeClass<E: RawRepresentable where E.RawValue == Int>{ func doSomething(e: E) { print(e.rawValue) } } class SomeEnumClass : SomeClass<SomeEnum> { } or directly class SomeOtherClass{ func doSomething<E: RawRepresentable where E.RawValue == Int>(e: E) { print(e.rawValue) } } UPDATE for swift3: enum SomeEnum: Int { case One, Two, … Read more

Where is the best place to locate enum types?

Why treat enums differently to other types? Keep them in the same namespace as they’re likely to be used – and assuming they’re going to be used by other classes, make them top-level types in their own files. The only type of type which I do commonly clump together is delegates – I sometimes have … Read more

How to get the number of elements (variants) in an enum as a constant value?

Update as of 2022 There’s a new function std::mem::variant_count in rust nightly version. Example to use by rust docs. use std::mem; enum Void {} enum Foo { A(&’static str), B(i32), C(i32) } assert_eq!(mem::variant_count::<Void>(), 0); assert_eq!(mem::variant_count::<Foo>(), 3); assert_eq!(mem::variant_count::<Option<!>>(), 2); assert_eq!(mem::variant_count::<Result<!, !>>(), 2);

How do I conditionally check if an enum is one variant or another?

First have a look at the free, official Rust book The Rust Programming Language, specifically the chapter on enums. match fn initialize(datastore: DatabaseType) { match datastore { DatabaseType::Memory => { // … } DatabaseType::RocksDB => { // … } } } if let fn initialize(datastore: DatabaseType) { if let DatabaseType::Memory = datastore { // … … Read more

Is there a way to print enum values?

You can derive an implementation of std::format::Debug: #[derive(Debug)] enum Suit { Heart, Diamond, Spade, Club } fn main() { let s = Suit::Heart; println!(“{:?}”, s); } It is not possible to derive Display because Display is aimed at displaying to humans and the compiler cannot automatically decide what is an appropriate style for that case. … Read more