Structs in Dart

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 {
  String name;
  int age;

  Person(this.name, this.age);

  Person.withName(String name) {
    this.name = name;
    this.age = 42;
  }
}

Here’s a constructor that initializes a Person with a given name.

void main() {
  // This syntax creates a new struct
  print(Person("Bob", 20));

  // You can name the fields when initializing a struct
  print(Person("Alice", 30));

  // Omitted fields will be zero-valued (default construction without values)
  var fred = Person("Fred", 0);
  print(fred);

  // Creating a struct with a constructor function
  var ann = Person.withName("Ann");
  print(ann);

  // Access struct fields with a dot
  var s = Person("Sean", 50);
  print(s.name);

  // Darts' structs are mutable
  s.age = 51;
  print(s.age);

  // Anonymous structs
  var dog = {'name': 'Rex', 'isGood': true};
  print(dog);
}

To run the program, just execute the Dart file.

$ dart run your_filename.dart
Person("Bob", 20)
Person("Alice", 30)
Person("Fred", 0)
Person("Ann", 42)
Sean
51
{name: Rex, isGood: true}

Now that we’ve seen how to create and use structs in Dart, let’s move on to more advanced features of the language.