News for hackers. Stuff that matters.
Re:Using enums to represent state in Rust by goku12 on Friday September 22, 2023 @10:40AM (#37612675)
I sometimes wish Rust had combined structs and enums into a single concept - same an enum. Structs would have been unnecessary. The compiler can simply avoid the tag or the union when a pure struct or a pure (c-type) enum is required, respectively.
Re:Using enums to represent state in Rust by bombela on Friday September 22, 2023 @02:18PM (#37615652)
> The compiler can simply avoid the tag or the union when a pure struct or a pure (c-type) enum is required, respectively.

I had to try:

  pub enum Foo {
      Foo { a: i32 },
  }
  
  impl Foo {
      pub fn new() -> Self {
        Foo::Foo { a: 42 }
      }
  
      pub fn get_a(Foo::Foo{a}: &Self) -> &i32 {
          a
      }
  }
At opt level above zero (-C opt-level=1) the tag is elided:

  example::Foo::new:
          mov     eax, 42
          ret
  
  example::Foo::get_a:
          mov     rax, rdi
          ret

https://godbolt.org/z/qKzMqvhb7
Re:Using enums to represent state in Rust by goku12 on Friday September 22, 2023 @11:08PM (#37620282)
That really does make structs superfluous, doesn't it? The only additional thing needed is a syntax sugar, where the variant name can be avoided if there is only one variant.
Re:Using enums to represent state in Rust by bombela on Saturday September 23, 2023 @12:02AM (#37620493)
Syntactic sugar to avoid the variant where there is only one, not only where used, but also when declared: enum Foo { Foo{...} }, what to do with the second Foo. And what about FFI (foreign function interface) where you have to maintain ABI compatibility over time. Factor all of that in, and it turns out Rust already has syntax for all of that: struct Foo {}.