Structs in Fortress

Our input specifies JavaScript as the target language. Here’s how the Go code example for structs is translated into JavaScript:

Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.

This person struct type has name and age fields.

class Person {
    constructor(name) {
        this.name = name;
        this.age = 0;
    }
}

newPerson constructs a new person struct with the given name.

function newPerson(name) {
    let p = new Person(name);
    p.age = 42;
    return p;
}

JavaScript is a garbage collected language; you can safely return a reference to a local variable - it will only be cleaned up by the garbage collector when there are no active references to it.

// Main execution
function main() {
    // This syntax creates a new struct
    console.log(new Person("Bob"));

    // You can name the fields when initializing a struct
    let alice = new Person("Alice");
    alice.age = 30;
    console.log(alice);

    // Omitted fields will be undefined
    let fred = new Person("Fred");
    console.log(fred);

    // Prefixing with an & yields a pointer to the struct
    let ann = new Person("Ann");
    ann.age = 40;
    console.log(ann);

    console.log(newPerson("Jon"));

    // Access struct fields with a dot
    let s = new Person("Sean");
    s.age = 50;
    console.log(s.name);

    // You can also use dots with struct pointers - the pointers are automatically dereferenced
    let sp = s;
    console.log(sp.age);

    // Structs are mutable
    sp.age = 51;
    console.log(sp.age);

    // If a struct type is only used for a single value, we 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.
    let dog = {
        name: "Rex",
        isGood: true
    };
    console.log(dog);
}

// Call the main function to execute the code
main();

Running the Code

To run the translated JavaScript code, you can save the code into a file struct_example.js and execute it using Node.js.

$ node struct_example.js

The expected output will be:

Person { name: 'Bob', age: 0 }
Person { name: 'Alice', age: 30 }
Person { name: 'Fred', age: 0 }
Person { name: 'Ann', age: 40 }
Person { name: 'Jon', age: 42 }
Sean
50
51
{ name: 'Rex', isGood: true }

Now that we can run and build basic JavaScript programs, let’s learn more about the language.