type MyEnum int
const (
A MyEnum = iota
B
C
D
) type MyEnum int
const (
A MyEnum = iota
B
C
D
)https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html...
(rust enums can have associated data too, but its not their main usage in idiomatic code)
That said I wonder why they named it enum.
Because it's a type-safe enumeration? ADTs are pretty much a superset of C-style enums, an ADT with all-dataless constructors is equivalent to a C enum:
enum Foo { Bar, Baz, Qux, Quux }
And members can converted to integrals: > println!("{}", Foo::Qux as u8);
2
With explicit integrals very much like C: > enum Foo { Bar = 5, Baz, Qux, Quux }
> println!("{}", Foo::Qux as u8);
7
Calling it "enum" makes it familiar to C developers[0], "union" would have been confusing for the same (as you can't just write one representation and read the other) and "type" is a tad too generic (and used for type aliases à la typedef).[0] even more so C++ developers as they have `enum class` which is also type-safe and not implicitly converted to integrals
OTOH I haven't written a line of Rust of yet, so enum might be more familiar in use.
The issue with `union` is it might hint at things which are not available (e.g. the union of an int and a float where you can access to the raw data as either).
A Rust enum is really an encoding of the `struct { enum, union }` pattern, but it degenerates to an enum if there's no union part (no data payload), not to a union. So calling it an enum makes more sense.
type Shape struct {
Rectangle *Rectangle
Circle *Circle
Triangle *Triangle
}
Then you send shapes on your channel rather than interface {}. If you want to enforce having only one element populated, make the struct members private and write: func NewRectangleShape(r *Rectangle) *Shape {
return &Shape{rectangle: r}
}"A circle, triangle, or rectangle" is not the same data structure as "Something that can be drawn". Certainly if you have a function that draws something given a Draw() method, having the function take a "Drawable" is appropriate. But it's not the only use case; sometimes you really mean "A circle, triangle, or rectangle" and in that case, a struct is absolutely what you want.