Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

C union declarations should correspond pretty closely to rust enum declarations.

It's a surprisingly important feature. Every large codebase I've worked on has clunky workarounds for storing heterogeneous types in collections.

Haven't seen a silver bullet; dynamic languages are great at this until you have to scale (either in lines of code, number of types or dataset size) and then they become unmanageable. Static languages force you to type a lot and build in-memory ETL-style transformations but scale better. Using SQL is another solution, but that separates you from the language's type-checker and can be another source of error.

Type safety at the serialization boundary was the promise of CORBA and protobuf but we need better tools. I hope we see more focus on ser/des types in the next generation of industry languages.



Close, but not quite: unless the type is NonZero, you need space for the tag.

c-style unions are in nightly behind a flag; they're not stable yet.


I think they meant that the use case corresponds closely, not the representation. Generally C unions get used the same place Rust unions would in a rust program (not vice versa though), unless they're being used for type punning, which is pretty rare anyway.


I meant if you have a large program where many types are C unions like:

    struct TaggedUnion {
        enum {T1, T2} type_id;
        union {type1 t1; type2 t2;} u;
    }
If the goal is to translate automatically to a rust enum declaration, that will be (a) possible to do with an automatic tool and (b) will give enhanced safety because it will force the type to be checked everywhere these values are used.


At least that one is really simple in Crystal:

  x = [] of Int32 | Char
  x << 42
  x << 'F'
=> [42, 'F']




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: