Structs in C++

Based on the Go code example provided, here is the translation to C++:

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.

struct person {
    std::string name;
    int age;
};

newPerson constructs a new person struct with the given name.

person* newPerson(std::string name) {
    person p = {name, 42};
    return new person(p);
}

This syntax creates a new struct.

#include <iostream>

int main() {
    person p1 = {"Bob", 20};
    std::cout << "{" << p1.name << " " << p1.age << "}\n";

    // You can name the fields when initializing a struct.
    person p2 = {"Alice", 30};
    std::cout << "{" << p2.name << " " << p2.age << "}\n";

    // Omitted fields will be zero-valued.
    person p3 = {"Fred", 0};
    std::cout << "{" << p3.name << " " << p3.age << "}\n";

    // An & prefix yields a pointer to the struct.
    person* p4 = new person{"Ann", 40};
    std::cout << "&{" << p4->name << " " << p4->age << "}\n";

    // It’s idiomatic to encapsulate new struct creation in constructor functions
    person* p5 = newPerson("Jon");
    std::cout << "&{" << p5->name << " " << p5->age << "}\n";

    // Access struct fields with a dot.
    person s = {"Sean", 50};
    std::cout << s.name << "\n";

    // You can also use dots with struct pointers - the pointers are automatically dereferenced.
    person* sp = &s;
    std::cout << sp->age << "\n";

    // Structs are mutable.
    sp->age = 51;
    std::cout << sp->age << "\n";

    // 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.
    struct {
        std::string name;
        bool isGood;
    } dog = {
        "Rex",
        true
    };
    std::cout << "{" << dog.name << " " << dog.isGood << "}\n";

    delete p4;
    delete p5;
    return 0;
}

To run the program, compile the code into an executable file and then run it.

$ g++ -o structs structs.cpp
$ ./structs
{Bob 20}
{Alice 30}
{Fred 0}
&{Ann 40}
&{Jon 42}
Sean
50
51
{Rex 1}

Next example: Methods.