import ballerina/io;
type Person {
    string name;
    int age = -1;
    Person parent;
    string status;
};function main (string[] args) {
    Person p1 = {};
    io:println(p1);
    Person p2 = {name:"Jack", age:20, parent:p1};
    io:println(p2);
    io:println(p2.name);
    io:println(p2["name"]);
    io:println(p2.parent.age);
    p1.name = "Peter";
    p1.age = 25;
    io:println(p1);
    io:println(p2);
}

Structs

In Ballerina, structs are collections of typed fields that allow you to create new, user-defined data types.

import ballerina/io;
type Person {
    string name;
    int age = -1;
    Person parent;
    string status;
};

Defining a Person struct. Contains field names and their types.
Optionally, for value type fields, can define the default value. Otherwise, the default value will be set to the zero-value.

function main (string[] args) {
    Person p1 = {};
    io:println(p1);

Create a person with default values.

    Person p2 = {name:"Jack", age:20, parent:p1};
    io:println(p2);

Create a person struct. Values can be set to any field when initializing. Other fields will have their default values.

    io:println(p2.name);
    io:println(p2["name"]);

Get a value of a field of a struct. Fields can be accessed using dot(.) notation or using index.

    io:println(p2.parent.age);

Get the field of a nested struct.

    p1.name = "Peter";
    p1.age = 25;
    io:println(p1);
    io:println(p2);
}

Set the value of a field.

$ ballerina run structs.bal
{name:"", age:-1, parent:null, status:""}
{name:"Jack", age:20, parent:{name:"", age:-1, parent:null, status:""}, status:""}
Jack
Jack
-1
{name:"Peter", age:25, parent:null, status:""}
{name:"Jack", age:20, parent:{name:"Peter", age:25, parent:null, status:""}, status:""}