Structures in Golang

GolangGolangBeginner
Practice Now

Introduction

Structure (struct) is a composite type that can be used to store different types of data. It can be used to implement more complex data structures. For instance, the items in a convenience store have attributes such as product name, category, and price. We can use a structure to represent them.

In this lab, we will learn about defining and using structures.

Knowledge Points:

  • Definition of a structure
  • Methods of a structure instance

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Golang`")) -.-> go/BasicsGroup(["`Basics`"]) go(("`Golang`")) -.-> go/DataTypesandStructuresGroup(["`Data Types and Structures`"]) go(("`Golang`")) -.-> go/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) go/BasicsGroup -.-> go/values("`Values`") go/BasicsGroup -.-> go/variables("`Variables`") go/DataTypesandStructuresGroup -.-> go/pointers("`Pointers`") go/DataTypesandStructuresGroup -.-> go/structs("`Structs`") go/ObjectOrientedProgrammingGroup -.-> go/methods("`Methods`") subgraph Lab Skills go/values -.-> lab-149097{{"`Structures in Golang`"}} go/variables -.-> lab-149097{{"`Structures in Golang`"}} go/pointers -.-> lab-149097{{"`Structures in Golang`"}} go/structs -.-> lab-149097{{"`Structures in Golang`"}} go/methods -.-> lab-149097{{"`Structures in Golang`"}} end

Definition of Structure

We can use the keywords type and struct to define a structure. The syntax is as follows:

type StructName struct {
    FieldName Type
    // ...
}

Where:

  • Type represents the specific type of the field name, which can be an integer, string, etc.
  • StructName must be unique within the same package.
  • The field names must be unique within the same structure.

Let's try it out. Let's define a convenience store:

type Store struct {
    ProductType string // product type
    ProductName string // product name
    Price       int    // product price
}

In the above code, we define a structure named Store for the convenience store, which includes the type, name, and price of the product.

Since the product type and product name fields are of the same type, we can simplify the code as follows:

type Store struct {
    ProductName, ProductType string
    Price                   int
}

Instantiation using var

In the previous section, we defined a convenience store structure Store, which describes the memory space. It will only be allocated memory and use the fields of the structure after instantiation.

We can use the var keyword to instantiate a structure:

var InstanceName Structure

Let's take a look at an example of instantiation. Create a file named struct.go and write the following code:

cd ~/project
touch struct.go
package main

import "fmt"

type Store struct {
    productName string
    productType string
    price       int
}

func main() {
    // Instantiate a structure using `var`
    var store1 Store
    // Assign values to the fields related to the instance store1
    store1.productType = "Drinks"
    store1.productName = "Coca-Cola"
    store1.price = 3

    fmt.Printf("store1:\n\t%s\n\t%s\n\t%d\n",
        store1.productType, store1.productName, store1.price)
}

Run the program:

go run struct.go

After running, the following result is displayed:

store1:
Drinks
Coca-Cola
3

In this program, we instantiated a convenience store using var and then assigned values to its fields using the . operator.

Initial Value of a Structure

What will be the value of an instantiated structure if we only initialize it without assigning a value? Let's take a look at the following code:

package main

import "fmt"

type Store struct {
    ProductName string
    ProductType string
    Price       int
}

func main() {
    // Instantiate a structure using `var`
    var lan1 Store
    // Print the structure value using %#v
    fmt.Printf("lan1: %#v\n", lan1)
}

Run the program:

go run struct.go

The result is as follows:

lan1: main.Store{ProductName:"", ProductType:"", Price:0}

We can see that when no initial value is specified, the value of the instantiated structure is the zero value of the corresponding type. For example, the string is empty, and the integer is 0.

Instantiation using new

In addition to using the var keyword for instantiation, we can also use the new keyword:

package main

import "fmt"

type Store struct {
    productName string
    productType string
    price       int
}

func main() {
    store := new(Store)
    // Use %T to output the type
    fmt.Printf("Type of store: %T\n", store)

    store.productType = "Daily Necessities"
    store.productName = "Umbrella"
    store.price = 20

    fmt.Printf("store:\n\t%s\n\t%s\n\t%d\n",
        store.productType, store.productName, store.price)
}

Run the program:

go run struct.go

The result is as follows:

Type of store: *main.Store
store:
        Daily Necessities
        Umbrella
        20

When using the new keyword for instantiation, the "instance" it creates is actually a pointer to the instance. The operation of assigning a value to the structure pointer is the same as assigning a value to a normal structure.

Instantiation using :=

Similarly, we can use := to instantiate a structure:

package main

import "fmt"

type Store struct {
    productName string
    productType string
    price       int
}

func main() {
    lan3 := Store{}
    lan3.productType = "Fresh Food"
    lan3.productName = "Taiwanese Meatballs"
    lan3.price = 20
    fmt.Printf("lan3:\n\t%s\n\t%s\n\t%d\n",
        lan3.productType, lan3.productName, lan3.price)
}

Run the program:

go run struct.go

The result is as follows:

lan3:
    Fresh Food
    Taiwanese Meatballs
    20

We can write initialization and assignment together, like this:

package main

import "fmt"

type Store struct {
    productName string
    productType string
    price       int
}

func main() {
    lan3 := Store{
        productType: "Fresh Food",
        productName: "Taiwanese Meatballs",
        price:       4,
    }
    fmt.Printf("lan3:\n\t%s\n\t%s\n\t%d\n",
        lan3.productType, lan3.productName, lan3.price)
}

Run the program:

go run struct.go

The result is as follows:

lan3:
    Fresh Food
    Taiwanese Meatballs
    4

When we need to assign values to all fields of a structure, we can write values in the order they are defined in the structure.

For example, we rewrite the lan3 instance as follows:

lan3 := Store{
        "Fresh Food",
        "Taiwanese Meatballs",
        4,
    }

Note: This syntax is only suitable for cases where values are assigned to all fields.

Summary

In this lab, we introduced structures and summarized the following knowledge points:

  • Structures are compound data types that can contain multiple different data types.
  • The value of an uninitialized structure is the zero value of the corresponding type.
  • Three methods of instantiating a structure.

Other Golang Tutorials you may like