Go Accessing Struct Fields 🎯

beginner
12 min

Go Accessing Struct Fields 🎯

Welcome to our deep dive into structs and field access in Go! By the end of this lesson, you'll be comfortable navigating and manipulating struct fields like a pro. Let's get started! 🎉

What are Structs? 📝

Structs, or structures, are custom data types in Go that allow you to group related data together. They are essential when you need to create complex data structures for real-world applications.

go
type Person struct { Name string Age int City string }

In the example above, Person is a struct with three fields: Name, Age, and City. Each field has its own type (string and int).

Accessing Struct Fields 💡

To access a struct field, you simply reference the struct variable, followed by the dot (.), and the field name.

go
func main() { var person Person person.Name = "John Doe" person.Age = 30 person.City = "New York" fmt.Println(person.Name) // Output: John Doe fmt.Println(person.Age) // Output: 30 fmt.Println(person.City) // Output: New York }

In the above example, we've defined a Person struct and set its fields using the assignment operator (=). Then, we accessed each field using the dot notation.

Updating Struct Fields 💡

To update a struct field, simply assign a new value to it, just as we did in the previous example.

go
func main() { var person Person person.Name = "John Doe" person.Age = 30 person.City = "New York" // Change the person's city person.City = "Los Angeles" fmt.Println(person.City) // Output: Los Angeles }

Struct Fields and Methods 💡

When defining a struct, you can also include methods that operate on the struct's fields. This can make your code cleaner and easier to understand.

go
type Person struct { Name string Age int City string Greet func() string } func (p Person) Greet() string { return "Hello, I'm " + p.Name + " from " + p.City } func main() { person := Person{ Name: "John Doe", Age: 30, City: "New York", } fmt.Println(person.Greet()) // Output: Hello, I'm John Doe from New York }

In the above example, we've added a Greet method to the Person struct. The method takes no arguments and returns a string. When we call Greet() on a Person variable, the method has access to the Name and City fields.

Quiz 💡

Quick Quiz
Question 1 of 1

How do you access the `Name` field of a `Person` struct in Go?

That's it for today! In the next lesson, we'll explore more about struct methods and dive deeper into Go programming. Keep coding! 🚀