Learning BSV‎ > ‎Data Types‎ > ‎



A structure (struct) is a composite type.  A struct value is a collection of values, each of which has a particular type and is identified by a member or field name.   A struct value contains all the members.  This is different from a tagged union, in which each value contains one of the members.  Struct member names must begin with a lowercase letter.  Each member name in a particular struct must be unique within the struct, but may be used in other structs or unions.


 typedef struct {Type member1;...Type membern}
         Structname deriving (Typeclass);

Syntax Examples

 typedef struct { int x; int y; } Coord;
 typedef struct { Addr pc; RegFile rf; Memory mem; }  Proc;
 typedef struct {
    Bool     flag;
    TDataY   coordX;
    TDataX   coordY;
  } TName deriving(Bits, Eq);

 typedef struct{
     Vector#(3, Bit#(8))   color;
     Bit#(4)               brightness;
     Bool                  blinking;
 } Pixel;

Assigning Values to a Struct

To access a struct member:

Example (using above struct Pixel)

 Vector#(256, Pixel)  screenLine;
    screenLine[0].color[1]    = 8'hFF;
    screenLine[0].brightness  = 4'd2;
    screenLine.blinking       = False;

Usage Tips

Split up large structures into smaller ones.

If your design only updates a few fields, keep those fields in their own structure; i.e., separate static from dynamic data.
  • Keep in mind that structures can contain other structures. With this split, one can have registers of small structures, and pass larger structures between modules as required.
  • Determine if your design requires a Register of a Vector or a Vector of Registers
A simple example, where name and idcode do not change, but the data and status are updated frequently.  It is better to break the structure up into 2 smaller structures, to avoid updating name and idcode every time data and/or status change.

typedef struct {
     Bit#(8)   name;
     UInt#(8)  idcode;
     Bit#(8)   data;
     Bool      status;
 } Record;            

 typedef struct {
     Bit#(8)   name;
     UInt#(8)  idcode;
 } RecordHead;
 typedef struct{
     Bit#(8)   data;
     Bool      status;
 } RecordData;