DEV Community

Cover image for Understanding Structs in Go: A Comprehensive Guide for Beginners
Avinash Chodavarapu
Avinash Chodavarapu

Posted on

Understanding Structs in Go: A Comprehensive Guide for Beginners

Introduction

Welcome to this beginner-friendly guide to one of Go's most powerful features: structs. In this post, we'll explore what structs are, how to define methods on them, and their practical uses. By the end, you'll understand why structs are such a vital part of Go programming.

Prerequisites

Before we dive in, it's assumed that you have a basic understanding of Go programming, including variables, basic data types, and functions. If you're new to Go or need a refresher on these concepts, I recommend going through the blog posts I've written previously. These posts will provide a solid foundation and make this guide easier to follow. Once you're comfortable with these basic concepts, you're ready to delve into the world of structs in Go!

What are Structs?

In Go, a struct is a composite data type. It groups together variables of different types into a single unit, much like a record in Pascal or a class in Python (without methods).

Consider this example:

type Employee struct {
    ID     int
    Name   string
    Salary float64
}
Enter fullscreen mode Exit fullscreen mode

Here we define a struct called Employee that groups an integer (ID), a string (Name), and a float (Salary).

Creating and Using Structs:

Once a struct type is defined, you can create an instance of it like this:

john := Employee{
    ID:     1,
    Name:   "John Doe",
    Salary: 50000,
}
Enter fullscreen mode Exit fullscreen mode

And then access its fields using the dot operator (.)

Accessing fields:

Image description

fmt.Println(john.Name) 
// Outputs: John Doe
Enter fullscreen mode Exit fullscreen mode

Methods on Structs:

In Go, a method is a function with a special type of parameter known as a receiver. This receiver enables the function to operate on a particular type (structs, in this case).

Here's the general syntax:

func (receiverType ReceiverName) MethodName(parameters) (returnType) {
    // Method body
}
Enter fullscreen mode Exit fullscreen mode

The receiver is declared in the parentheses before the function name. This is a struct type, and it ties the function (method) to the struct. When a function has a receiver, it can be called as a method on an instance of the receiver type.

Let's look at an example. Suppose we have a struct representing a rectangle:

type Rectangle struct {
    Length float64
    Width  float64
}
Enter fullscreen mode Exit fullscreen mode

We can now define a method that calculates the area of the rectangle:

func (r Rectangle) Area() float64 {
    return r.Length * r.Width
}
Enter fullscreen mode Exit fullscreen mode

In this method, r is the receiver, and its type is Rectangle. The Area method can now be called on any Rectangle instance:

r := Rectangle{Length: 4, Width: 5}
fmt.Println(r.Area())  // Outputs: 20
Enter fullscreen mode Exit fullscreen mode

It's important to note that, by default, methods in Go use a value receiver, meaning they receive a copy of the value, not the value itself. If you want the method to modify the original struct, you should use a pointer receiver:

func (r *Rectangle) SetLength(newLength float64) {
    r.Length = newLength
}

r := Rectangle{Length: 4, Width: 5}
r.SetLength(10)
fmt.Println(r.Length)  // Outputs: 10
Enter fullscreen mode Exit fullscreen mode

In this example, SetLength method changes the original Rectangle struct because it's defined with a pointer receiver (*Rectangle).

I hope this clarifies the concept of methods on structs in Go. Remember that practicing with your own examples will help you in better understanding.

Uses of Structs:

So, why are structs important? Here are a few reasons:

  1. Grouping Data: Struct allow you to group different data into one entity, making it much easier to work with related data.
  2. Creating Custom Types: Structs allow you to create your own custom data types. This makes your code cleaner and easier to understand.
  3. Methods: Defining methods on structs makes them behave like classes in other languages.
  4. Implementing Interfaces: In Go, a type is said to implement an interface if it contains all the methods defined in that interface. Using structs to implement interfaces gives you more flexible and organized code.

Differences between Dictionary, Object and Structs:

Feature Go Struct JavaScript Object Python Dictionary
Type Safety Yes, fields are statically typed. No, properties can be any type. No, keys and values can be any type.
Method Support Yes, methods can be defined on structs. Yes, methods can be added to objects. No, dictionaries are a basic data type without methods.
Order of Elements Yes, the order of fields is fixed. No, order of properties is not guaranteed (though it's preserved in practice in most modern JS engines). No, until Python 3.7 order was not preserved. Since Python 3.7+, order of insertion is preserved.
Accessing Non-Existent Keys Raises a compile-time error. Returns undefined. Raises a KeyError at runtime.

Conclusion

Structs are one of Go's most powerful features, allowing you to create custom data types and methods that make your code cleaner, more organized, and more efficient. As you continue your Go journey, you'll find structs to be an invaluable tool in your programming toolkit.

Questions?

Got any questions or comments about structs in Go? Drop them below, and let's start a conversation!

Top comments (0)