Go Structs Introduction 🎯

beginner
22 min

Go Structs Introduction 🎯

Welcome to the exciting world of Go Structs! In this lesson, we'll learn how to create, use, and customize data structures in Go. By the end, you'll be able to build clean and efficient code with ease. 📝 Note: Go Structs are similar to classes in other programming languages, allowing us to group related data and functions together.

Understanding Structs 💡

Let's start with the basics. In Go, we define Structs using the struct keyword. A simple example of a Struct might look like this:

go
type Person struct { Name string Age int }

In this example, we've defined a Person Struct with two fields: Name and Age. Each field has a type associated with it, in this case string and int.

Creating Struct Instances 💡

Now that we have our Struct defined, we can create instances of it! Let's create a Person instance:

go
johnDoe := Person{Name: "John Doe", Age: 30}

Here, we've created a new Person instance called johnDoe with a name of "John Doe" and an age of 30.

Accessing and Modifying Fields 💡

To access or modify the fields of a Struct, we use dot notation:

go
fmt.Println(johnDoe.Name) // Output: John Doe johnDoe.Age = 31

Here, we've printed the name of johnDoe and then updated his age to 31.

Methods on Structs 💡

In addition to fields, we can also define methods on our Structs. Here's an example of a Speak method for our Person Struct:

go
type Person struct { Name string Age int Speak func() string } func (p Person) Speak() string { return fmt.Sprintf("Hello, I am %s and I am %d years old.", p.Name, p.Age) } johnDoe.Speak() // Output: Hello, I am John Doe and I am 31 years old.

In this example, we've added a Speak method to our Person Struct. The method returns a personalized greeting using the p.Name and p.Age fields.

Struct Types 📝 Note:

Go has three types of Structs:

  1. Named Structs: These are the Structs we've been working with. They have a name and can contain fields and methods.

  2. Anonymous Structs: These are Structs without a name, typically used when we don't need a specific name.

  3. Composite Literal: This is a shorthand way to create a Struct instance by listing its fields and their values within curly braces.

Quiz 💡

Quick Quiz
Question 1 of 1

What is the purpose of a Struct in Go?

That's it for our introduction to Go Structs! In the next lesson, we'll dive deeper into Struct methods and explore more advanced concepts. Until then, happy coding! 💡 Pro Tip: Be sure to practice creating and using Structs in your own code to solidify your understanding. 📝 Note: You can find more resources on CodeYourCraft to help you along the way!