Lesson 3
Introduction to Structs
Introduction to Structs

Welcome back! In your previous lessons, we explored how to structure our Elixir code using functions and modules. These tools helped us write more organized and reusable code. Today, we're going to take another step forward by learning about structs in Elixir. Structs allow us to define custom data types, making our code more expressive and easier to read.

What You'll Learn

In this section, we'll cover the basics of structs in Elixir. Specifically, you will learn:

  1. How to define a struct.
  2. How to create and use instances of a struct.
  3. The benefits of using structs in your programs.

We'll start with a simple example to illustrate these points:

Elixir
1defmodule User do 2 defstruct name: "", age: 0 3end 4 5defmodule Main do 6 def run do 7 user = %User{name: "Alice", age: 30} 8 IO.inspect(user) 9 end 10end 11 12Main.run()

In the above example, we define a User struct with two fields: name and age. Then, we create an instance of this struct and print it using IO.inspect.

Let's break down the code step by step:

  1. We define a User struct using the defmodule and defstruct macros. The defstruct macro specifies the fields of the struct, along with their default values. In this case, the User struct has two fields: name (with a default value of "") and age (with a default value of 0).
  2. We create an instance of the User struct with the name "Alice" and age 30. The %User{} syntax is used to create a struct instance with the specified field values.
  3. The IO.inspect(user) function prints the user struct to the console.
Why Structs Are Important

Structs are essential in Elixir for several reasons:

  1. Data Organization: Structs allow you to bundle related data together, making your code more organized. For example, if you're working on a user management system, having a User struct helps you keep user-related data in one place.

  2. Readability: Using structs makes your code more readable. When you see a %User{} struct, you immediately understand that it represents a user, making your code easier to follow and maintain.

  3. Type Safety: Structs enforce a defined set of fields, reducing the likelihood of errors due to misspelled or missing keys. This type of safety makes your programs more robust and less prone to bugs.

Structs improve the clarity and reliability of your code, which is especially valuable as your projects grow in size and complexity. Are you ready to dive in and see how structs can make your code even better? Let's move on to the practice section!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.