#Extending enums

4 messages · Page 1 of 1 (latest)

fringe jetty
#

Is there some kind of way to allow you to extend or shorten an enum?
For example, I have an enum:

enum Planets {
    Mercury(f64, f64),
    Venus(f64, f64),
    Earth(f64, f64),
    //...
    Neptune(f64, f64)
}```
Let's say this enum is in a lib, and I would like to allow whoever is using the lib to extend the enum on their end without modifying the source code;
Is there some kind of crate for that? Alternatively a macro?
Something to allow you something like this;
```rust
struct Pluto(f64, f64);

extend_enum!(Planets, Pluto);

fn select_planet(planet: Planets) -> Planets {
    match planets_enum {
    Planets::Mercury(x, y) => {},
    Planets::Venus(x, y) => {},
    //...
    Planets::Pluto(x, y) => {},
}```
#

Extending enums

wheat sand
#

Short answer is no. There's some things you can do instead, though.

  • Make Planets a trait, and convert the variants into structs that implement the trait. Then your functions can take a generic or possibly dyn Planets.

  • Make this a struct that holds the planet as a member:

struct Planets {
  planet_id: u8,
  data: (f64, f64),
}
const MERCURY: u8 = 1;
const VENUS: u8 = 2;
const EARTH: u8 = 3;
```This doesn't forbid collisions, unlike the trait. You could possibly upgrade the `u8` to `u16` later if you need more than 256 planets, but you'd need to be cautious with how users define new planets.

- Have the library user create a new enum. This might be good if the enum is just a template and doesn't need to interoperate with your library or other uses of your library. A macro can do this. You could also combine this with a trait to bring back some interoperability.
fringe jetty