Structs in Wolfram Language

Structs

Wolfram Language’s Association is similar to a struct in other programming languages. It is a collection of fields and can be used to group data together.

Creating a person Association with name and age fields

person = <|"name" -> "name", "age" -> 0|>;

Constructing a new person Association with the given name

newPerson[name_] := Module[{p},
  p = <|"name" -> name, "age" -> 42|>;
  p
];

Wolfram Language automatically manages memory and garbage collection, so local variables will be maintained as long as there are references to them.

Main function to demonstrate usage

main[] := Module[{person1, person2, person3, personPtr, personJon, s, sp, dog},
  (* This syntax creates a new Association. *)
  Print[<|"name" -> "Bob", "age" -> 20|>];

  (* You can name the fields when initializing an Association. *)
  Print[<|"name" -> "Alice", "age" -> 30|>];

  (* Omitted fields will be zero-valued (which is interpreted as 0 for integers). *)
  Print[<|"name" -> "Fred"|>];

  (* An Association with a pointer is just another reference. *)
  personPtr = <|"name" -> "Ann", "age" -> 40|>;
  Print[personPtr];

  (* Encapsulating new struct creation in constructor functions *)
  personJon = newPerson["Jon"];
  Print[personJon];

  (* Access Association fields with a key. *)
  s = <|"name" -> "Sean", "age" -> 50|>;
  Print[s["name"]];

  (* You can also use keys with Association references. *)
  sp = s;
  Print[sp["age"]];

  (* Associations are mutable. *)
  sp["age"] = 51;
  Print[sp["age"]];

  (* If a struct type is only used for a single value, you don’t have to give it a name. The value can have an anonymous struct type. This technique is commonly used for table-driven tests. *)
  dog = <|"name" -> "Rex", "isGood" -> True|>;
  Print[dog];
];

main[];

Output

To run the program, load the code in a Wolfram Language environment and execute it.

main[]

Output:

<|name -> Bob, age -> 20|>
<|name -> Alice, age -> 30|>
<|name -> Fred, age -> 0|>
<|name -> Ann, age -> 40|>
<|name -> Jon, age -> 42|>
Sean
50
51
<|name -> Rex, isGood -> True|>

This concludes the example of using Associations (similar to structs) in Wolfram Language to manage and manipulate grouped data.