Union and struct #raw_union

Hi everyone.
I found it kinda strange that we have both union { ... } type which is tagged union, and to create C-like union we’re using struct #raw_union { ... }.

Isn’t it more logical to create such directive for union type? Or is the union type completely different than struct so it would be problematic?

1 Like

The regular union has some additional compiler magic and syntax built around it that play very nice with the distinct type system. It wouldn’t make any sense for a raw union. The elements of a union are not named:

Foo :: union {
    string,
    int,
}

Raw unions have more complex use cases than a simple tagged union. Imagine having to work with that syntax to interface with a C library’s union. You would probably end up making distinct types for all the members just so things could be named. One of the primary uses of unions and structs in C are used to control memory layout, and they are commonly used together. For an example, check out the monstrosity that is the Sig_Info struct in core/sys/linux/types.odin.

So, the syntax for declaration and usage are different. The syntax for declaring and using raw union is identical to a struct. So, in my opinion, having it as a directive on a struct makes more sense. It behaves like a struct with a different layout in every sense.

2 Likes

AFAIK union in Odin doesn’t have named members. The C-style union hence is more closer to struct, so makes sense to have the compiler directive for it.

1 Like