Structs in Modelica

Based on the provided input, here is the appropriate translation of the Go code example to Modelica:


Modelica’s record constructs are the counterparts of structs in some other languages. They’re useful for grouping data together to form records.

This Person record type has name and age fields.

record Person
  String name;
  Integer age;
end Person;

newPerson constructs a new Person record with the given name.

function newPerson
  input String name;
  output Person p;
algorithm
  p.name := name;
  p.age := 42;
end newPerson;

This creates a new record.

model Example
  Person p1, p2, p3, p4, p5, p6;
initial algorithm
  p1 := Person(name = "Bob", age = 20);
  p2 := Person(name = "Alice", age = 30);
  p3 := Person(name = "Fred", age = 0);  // Omitted fields will be zero-valued
  p4 := Person(name = "Ann", age = 40);  // This syntax creates a new record with fields initialized
  p5 := newPerson("Jon");  // It's idiomatic to use constructor functions
  p6 := Person(name = "Sean", age = 50);  // Access record fields with a dot

  // You can also use dots with record references
  Integer age := p6.age;
  // Records are mutable
  p6.age := 51;
  // Anonymous record type
  record Dog
    String name;
    Boolean isGood;
  end Dog;

  Dog dog;
  dog := Dog(name = "Rex", isGood = true);
end Example;

To run the program, put the code in Example.mo and simulate it using your Modelica environment.

When you simulate the Example model, it will initialize several Person records and demonstrate various operations on them.


Next example: Methods