Struct Embedding in Modelica

model StructEmbedding
  record Base
    Integer num;
  end Base;
  
  function describe
    input Base b;
    output String description;
  algorithm
    description := "base with num=" + String(b.num);
  end describe;
  
  record Container
    extends Base;
    String str;
  end Container;
  
  Container co(num=1, str="some name");
equation
  when initial() then
    Modelica.Utilities.Streams.print("co={num: " + String(co.num) + ", str: " + co.str + "}");
    Modelica.Utilities.Streams.print("also num: " + String(co.num));
    Modelica.Utilities.Streams.print("describe: " + describe(co));
  end when;
end StructEmbedding;

In Modelica, we don’t have the concept of struct embedding as in some other languages. However, we can achieve similar functionality using inheritance. Here’s an explanation of the Modelica code:

Modelica supports composition of types through inheritance. This is similar to embedding in other languages but with some differences.

We define a Base record with an Integer field num:

record Base
  Integer num;
end Base;

We then define a function describe that takes a Base as input and returns a description string:

function describe
  input Base b;
  output String description;
algorithm
  description := "base with num=" + String(b.num);
end describe;

A Container record inherits from Base and adds a String field str:

record Container
  extends Base;
  String str;
end Container;

In the main model, we create an instance of Container:

Container co(num=1, str="some name");

We can access the fields directly on co, e.g., co.num and co.str.

To simulate the output, we use the initial() event and Modelica’s stream printing functionality:

equation
  when initial() then
    Modelica.Utilities.Streams.print("co={num: " + String(co.num) + ", str: " + co.str + "}");
    Modelica.Utilities.Streams.print("also num: " + String(co.num));
    Modelica.Utilities.Streams.print("describe: " + describe(co));
  end when;

This will print the values when the simulation starts.

Note that Modelica doesn’t have interfaces or method implementations on records in the same way as some other languages. The describe function is separate from the Base record, but can be called with any record that extends Base.

When you simulate this model, you should see output similar to:

co={num: 1, str: some name}
also num: 1
describe: base with num=1

This example demonstrates how Modelica uses inheritance to compose types, which is conceptually similar to struct embedding in other languages.