Lesson 1
Crafting Custom Data Types: An Introduction to Structs in Go
Topic Overview and Importance

Welcome! Today, we're exploring structs in Go. Structs are critical for grouping related data. For instance, a library book has properties such as the title, author, and publication year; these can all be represented using a struct in Go. Our goal is to understand how to define, create, and utilize structs in Go.

Introduction to Structs in Go

Structs in Go collate related data, thereby facilitating code organization. Many real-world objects can be modeled as structs.

Creating a struct involves producing a custom type with a set of associated properties, referred to as fields. For example, a Book struct can contain fields like Title, Author, and Year. The declaration of these fields aligns with the pattern fieldName fieldType.

Let's implement it:

Go
1type Book struct { 2 Title string 3 Author string 4 Year int 5}

Now, we have a Book type that includes associated data, marking it as a unique, custom type.

Creating Structs in Go

Once you've defined a struct, creating an instance of it is straightforward:

Go
1func main() { 2 var book1 Book 3 book1.Title = "To Kill a Mockingbird" 4 book1.Author = "Harper Lee" 5 book1.Year = 1960 6 7 fmt.Println(book1) // Output: {To Kill a Mockingbird Harper Lee 1960} 8}

In the code above, we declare book1 as a type Book and then assign values to the book1 fields using dot notation.

Using Structs Effectively in Go

Structs enable us to manage complex data in an organized fashion. They become indispensable when dealing with large programs that comprise multiple complex data relationships. For instance, in the following code, we add multiple books to a slice:

Go
1func main() { 2 book1 := Book{"To Kill a Mockingbird", "Harper Lee", 1960} 3 book2 := Book{Title: "1984", Author: "George Orwell", Year: 1949} 4 5 books := []Book{book1, book2} 6 7 for _, book := range books { 8 fmt.Println(book) // Output: 9 // {To Kill a Mockingbird Harper Lee 1960} 10 // {1984 George Orwell 1949} 11 } 12}
Lesson Summary and Practice

We've covered a significant concept — structs in Go. We've learned how to define, create, and use them. Going forward, we'll delve into using methods with structs and explore how they function in complex scenarios. Enjoy your practice!

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