Structs in Ada

Based on the input provided, the specified target language is Ada. Here’s the translation of the example code to Ada, along with the corresponding explanation:

Ada Structs Example

Ada doesn’t have structs in the same way as some other languages, but it does have records which serve a similar purpose for grouping data together.

with Ada.Text_IO; use Ada.Text_IO;

procedure Main is

   type Person is record
      Name : String (1 .. 100);
      Age  : Integer;
   end record;

   function New_Person(Name : String) return access Person is
      P : aliased Person := (Name => Name, Age => 42);
   begin
      return P'Access;
   end New_Person;

begin
   -- This syntax creates a new record instance
   declare
      Bob : Person := (Name => "Bob", Age => 20);
   begin
      Put_Line(Bob.Name & " " & Integer'Image(Bob.Age));
   end;

   -- You can name the fields when initializing a record
   declare
      Alice : Person := (Name => "Alice", Age => 30);
   begin
      Put_Line(Alice.Name & " " & Integer'Image(Alice.Age));
   end;

   -- Omitted fields will be zero-valued (default values)
   declare
      Fred : Person := (Name => "Fred", Age => 0);
   begin
      Put_Line(Fred.Name & " " & Integer'Image(Fred.Age));
   end;

   -- Accessing through a pointer
   declare
      Ann : access Person := new Person'(Name => "Ann", Age => 40);
   begin
      Put_Line(Ann.all.Name & " " & Integer'Image(Ann.all.Age));
   end;

   -- Using constructor function
   declare
      Jon : access Person := New_Person("Jon");
   begin
      Put_Line(Jon.all.Name & " " & Integer'Image(Jon.all.Age));
   end;

   -- Access record fields with a dot
   declare
      Sean : Person := (Name => "Sean", Age => 50);
   begin
      Put_Line(Sean.Name);
      Put_Line(Integer'Image(Sean.Age));
   end;

   -- Using a pointer to modify and access fields
   declare
      Sp : access Person := new Person'(Name => "Sean", Age => 50);
   begin
      Sp.Age := 51;
      Put_Line(Integer'Image(Sp.Age));
   end;

   -- Example of an anonymous record type for a single value
   declare
      type Dog is record
         Name  : String (1 .. 100);
         Is_Good : Boolean;
      end record;

      Rex : Dog := (Name => "Rex", Is_Good => True);
   begin
      Put_Line(Rex.Name & " " & Boolean'Image(Rex.Is_Good));
   end;

end Main;

To run the program, compile the code with your Ada compiler and then execute the resulting binary.

$ gnatmake main.adb
$ ./main

Output:

Bob 20
Alice 30
Fred 0
Ann 40
Jon 42
Sean
50
51
Rex TRUE

In this example, records are used to group together fields of data. You can initialize them with specific values, use functions to create them, and even work with pointers to modify them. This flexibility allows for structured and maintainable code.