Structs in Elm

Go by Example: Structs

JavaScript’s objects can be utilized in a similar way to structs in Go. Here’s how you can translate the example:

Structs in Go are used to create collections of fields. They’re useful for grouping data to form records. JavaScript doesn’t have structs, but we can use objects instead.

This example demonstrates various ways of using objects to the same effect.

// This person object type has name and age fields.
class Person {
  constructor(name) {
    this.name = name;
    this.age = 42;
  }
}

function newPerson(name) {
  return new Person(name);
}

// You can create a new object by directly assigning values.
console.log({ name: "Bob", age: 20 });

// You can name the fields when initializing an object.
console.log({ name: "Alice", age: 30 });

// Omitted fields will be undefined.
console.log({ name: "Fred" });

// Creating a pointer to an object.
let person = { name: "Ann", age: 40 };
console.log(person);

// It’s idiomatic to encapsulate new object creation in the constructor function
console.log(newPerson("Jon"));

// Access object fields with a dot.
let s = { name: "Sean", age: 50 };
console.log(s.name);

// You can also use dots with object references and
// modify the objects since they are mutable.
let sp = s;
console.log(sp.age);

sp.age = 51;
console.log(sp.age);

// An anonymous object type.
let dog = {
  name: "Rex",
  isGood: true,
};
console.log(dog);

To run the JavaScript code, you can use Node.js or any modern web browser. Save the code in a file named structs.js and run it with Node.js:

$ node structs.js

Expected output:

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

By using objects and classes in JavaScript, you can achieve similar semantics to structs in Go. With this understanding, let’s explore more about how to manage structured data in JavaScript.