Designing Entities with Structs

Learn how to create structs to describe entities.

Programming language entities and data types are not enough when we’re building a larger application. We need to create new data entities to express the application domain. In Elixir, we employ structs. We covered how to use them in the lesson Unpacking Values from Lists, Maps, and Structs, in Chapter 4, but now we’ll see how to create them.

We’ll create a struct that represents the player’s hero. Then we’ll organize our application, separating the domain entities from CLI code by listing the heroes’ options to the player. Then we’ll use some Mix command-line functions to let the player choose a hero. The first step is to build a struct to describe the Character domain entity.

Creating the character with structs

We’ll build a struct that will hold the properties related to the character. The character will be consistent across the entire application since structs don’t let us add new attributes beyond their definition. Let’s create a file that will have the struct in the following directory, under lib:

Get hands-on with 1200+ tech skills courses.