Skip to main content
Published on

struct in Go

Share:

Introduction

In Go, a "struct" is a composite collection of fields that allows you to group variables of different types. Structs are extremely useful for defining and creating custom data types, providing an organized way to represent entities and their attributes.

Defining and Initializing structs

To define a struct, we use the type keyword followed by the struct name and the struct keyword:

type Person struct {
  Name    string
  Age     int
  Email   string
}

To initialize a struct, we can assign values to its fields using curly-brace syntax:

p := Person{"Nelson", 28, "[email protected]"}

Or using field names:

p := Person{
  Name:  "Nelson",
  Age:   28,
  Email: "[email protected]",
}

Accessing struct Fields

To access a specific field of the struct, we use the . operator:

name := p.Name  // "Nelson"
age  := p.Age   // 28

Nested Structs

It is possible to have structs inside other structs, a feature that can be useful for representing hierarchical or complex relationships:

type Address struct {
  Street  string
  City    string
  Country string
}

type Person struct {
  Name     string
  Age      int
  Location Address
}

Pointers to structs

Just like other variables in Go, structs can also be referenced using pointers:

pointerToPerson := &p
pointerToPerson.Name = "Peter"  // Changes the name in the original struct

Methods and structs

In Go, we can define specific methods for structs, allowing specific operations to be performed with or on those structs:

func (p Person) Introduce() string {
  return "Hello, my name is " + p.Name
}

message := p.Introduce()  // "Hello, my name is Nelson"

Conclusion

Structs in Go are powerful and flexible tools that allow us to create clear and organized representations of entities and their attributes. Mastering structs is essential for any Go developer who wants to build robust and well-structured applications.

Happy coding!