Defining and Using Structs in Go

Structs are one of the fundamental types in the Go programming language. They allow you to define your own data structures by combining one or more variables with different data types into a single entity. In this article, we'll explore how to define and use structs in Go.

Defining a Struct

To define a struct in Go, you need to use the type keyword followed by the name of the struct and the keyword struct. The struct fields are defined inside curly braces {}.

type Person struct {
    name string
    age  int
}

Here, we define a struct called Person with two fields: name of type string and age of type int.

Creating Instances of a Struct

Once you have defined a struct, you can create instances of it, also known as struct literals. To create a struct literal, you simply specify the values for each field in the order they are defined.

person := Person{
    name: "John",
    age:  25,
}

Here, we create a new instance of the Person struct and assign it to the person variable. We provide values for the name and age fields.

Accessing Struct Fields

To access the fields of a struct, you use the dot (.) operator followed by the field name. For example:

fmt.Println(person.name)
fmt.Println(person.age)

This would output:

John
25

Modifying Struct Fields

Struct fields can be modified by assigning a new value using the dot (.) operator:

person.age = 30
fmt.Println(person.age)

This would output:

30

Anonymous Structs

In some cases, you may not need to define a named struct and can use anonymous structs instead. Anonymous structs don't have a defined name, but they allow you to work with temporary data structures easily.

person := struct {
    name string
    age  int
}{
    name: "Alice",
    age:  20,
}

Here, we define an anonymous struct with name and age fields and create an instance of it in one go.

Embedding Structs

Go supports struct embedding, where a struct can include another struct as one of its fields. This allows for composition and code reuse.

type Address struct {
    street  string
    city    string
    country string
}

type Person struct {
    name    string
    age     int
    address Address
}

In this example, the Person struct embeds the Address struct as a field. This means that a Person instance will have access to all the fields and methods defined in both the Person and Address structs.

Conclusion

Structs in Go provide a powerful way to define and work with custom data structures. By combining different data types into a single entity, you can create complex and well-organized code. Understanding how to define and use structs is essential knowledge for any Go programmer.


noob to master © copyleft