Skip to content

Proposal: Support nested anonymous struct and unions. #985

@bheads

Description

@bheads

Details of Exactly What was once Accepted
Details of why we went back on that and rejected this issue


Proposal: Support nested anonymous struct and unions

Section Value
Author: Byron Heads
Implementation:
Status: Draft

Abstract

A useful and common pattern found in a few other languages is the ability for structs and unions to contain anonymous structs and unions.

Example: Views into packed unions

const ARGBColor = packed union {
   bytes: u32,
   packed struct {
      a: u8,
      r: u8,
      g: u8,
      b: u8,
   };

  var color = ARGBColor{ .a = 0, .r = 255, .g = 0, .b = 255};
  color.r = 128;

  glFunction(color.bytes);
}
const VirtualRegister32 = packed union {
  F32: u32,
  packed struct {
      H16: packed union {
        F16 : u16
        packed struct {
          H8: u8,
          L8: u8
       },
       L16 = packed union {
         F16 : u16
         packed struct {
           H8: u8,
           L8: u8
      }
  }
};

car r1 = VirtualRegister32{.F32 = 0};

r.L16.L8 = 9;

Example: Struct OOP

struct base { 
  int type_id; 
  struct base *next;
}; 

 struct derived { 
  struct base; /* anonymous */ 
int a_new_field; ... }; 

Pros

  • Removes the need to name nested struts where the name is not meaningful
  • Can reduce the need to cast on structs and union types (especially when working with C)
  • Reduces the need to property functions

Cons

  • Could add confusion at the call site
  • Can be solved by casting and property functions
  • Can by solved by naming the nested struct

Metadata

Metadata

Assignees

No one assigned

    Labels

    proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions