golang

Golang Struct

For short, a structure or struct is a collection of fields with defined data types. Structures are very useful and improve flexibility in programs. Structures are probably your best bet if you have data that is best represented as a unit. Think of it as a lightweight version of object-oriented programming.

Go allows you to create and use structures using either built-in or user-defined types.

This guide will take a trip and explore how structures work in the Go programming language.

Declaring a Struct

The syntax below shows how to create struct in Go:

typestruct_namestruct {
    field_1 data_type
    field_2 data_type
    ...
    field_Ndata_type
}

We start by calling the type keyword. Next comes the name of the structure. The name of the structure can be anything user-defined (as long as it follows the rules of naming in Go). We then use the struct keyword, followed by a pair of curly braces.

Inside the braces, we define various fields that make up the structure. The field name is followed by its data type.

Declare Struct – Example

The example code below defines a struct called employee. It contains 5 fields with various data types.

typeEmployee struct {
    Name       string
    Age        int
    Retired    bool
    Department string
    Salary     float64
}

The above creates an Employee struct containing fields of various types.

NOTE: If you want to export the structure and its fields to other packages, ensure the names start with Uppercase letters. Otherwise, the scope is limited to that package.

Structure Instantiation

Defining a structure means we only create a blueprint. To create an object out of the struct, we need to create an instance of it.

To create an instance of a class in Go, start with the var keyword followed by the name of the instance.

The example below creates an instance of the Employee structure.

var emp Employee

Once we create an instance of the struct, we can access the fields using the dot notation as shown:

var emp Employee
emp.Name ="Thomas J"
emp.Age = 35
emp.Retired = false
emp.Department = "DevOps Engineer"
emp.Salary = 130000.50

Once we set the fields of the instace, we can print it as:

fmt.Println(emp)

The above snippet returns:

$ go run structs.go

{Thomas J 35 false DevOps Engineer 130000.5}

Struct Instantiation – Literal

You can also create an instance of a struct using the struct literal method. The example below shows uses struct literal to create an instance of a struct.

var emp1 = Employee{"Mary A", 26, false, "Game Developer", 150000.10}

fmt.Println(emp1)

The above example creates an instance of the class and sets the fields without using the dot-notation.

Struct Instantiation – New Keyword

If you don’t want to set the values during instance creation, you can use the new keyword. For example:

var emp2 = new(Employee)

Once created, we can access the instance fields and set values as:

emp2.Name = "Judy L"

emp2.Age = 60

emp2.Retired = true

emp2.Department = "Human Resources"

emp2.Salary = 119000.99

Access Struct Fields

To access the fields of a struct, go provide us with the dot operator. We start with the name of the structure instance and then the name of the field.

For example, to get the name of the emp2, we can do:

fmt.Println(emp2.Name)

This should return the value stored by the specified field.

Struct Methods

We can also add a method to a structure using the method receiver. Consider the example below that creates a method for the Employee structure.

func (e Employee) Info() string {

fmt.Printf("Name: %s\n Age: %d\n Retired: %t\n Department: %s\n Salary: %f\n", e.Name, e.Age, e.Retired, e.Department, e.Salary)

return "Done"

}

Once we have the method declared, we can create an instance and set the fields as:

var e Employee

e.Name = "Thomas J"

e.Age = 35

e.Retired = false

e.Department = "DevOps Engineer"

e.Salary = 130000.50

Finally, we can call the method as:

fmt.Println(e.Info())

Upon the method call, we should get an output as:

Name: Thomas J

Age: 35

Retired: false

Department: DevOps Engineer

Salary: 130000.500000

Done

Struct Field Type

You can find out the type of field using the reflect package. For example, to get the type of the Retired field, we can do:

fmt.Println(reflect.TypeOf(e.Retired))

The code above returns the field type as:

::output

bool

Struct Comparison

You can check if a struct is equal to another using the comparison operator. Note that a struct is defined as equal if all the fields have equal value.

NOTE: Not all data types are comparable.

The example below creates two structures and compares them using the == operator.


var e Employee
    e.Name = "Thomas J"
    e.Age = 35
    e.Retired = false
    e.Department = "DevOps Engineer"
    e.Salary = 130000.50
    var emp2 = new(Employee)
    emp2.Name = "Judy L"
    emp2.Age = 60
    emp2.Retired = true
    emp2.Department = "Human Resources"
    emp2.Salary = 119000.99

    if e == *emp2 {
        fmt.Println("structures are equal")
    } else {
        fmt.Println("structures not equal")
    }

Since the structures are not equal, the else block is executed.

HINT: empty and zero values are considered equal.

Conclusion

Phew!

That was an outstanding tutorial on working with structures in Go lang. This tutorial, however, only covers the basics. There are lot more operations you can do with structures.

Keep practicing, and check out our Go tutorials to learn more.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list