Defining and Using Structures in C

GoGoBeginner
Practice Now

Introduction

Structure (struct) is a compound type that can be used to store different types of data. It can be used to implement more complex data structures. For example, 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(("`Go`")) -.-> go/BasicsGroup(["`Basics`"]) go(("`Go`")) -.-> go/FunctionsandControlFlowGroup(["`Functions and Control Flow`"]) go(("`Go`")) -.-> go/DataTypesandStructuresGroup(["`Data Types and Structures`"]) go(("`Go`")) -.-> go/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) go/BasicsGroup -.-> go/variables("`Variables`") go/FunctionsandControlFlowGroup -.-> go/functions("`Functions`") go/DataTypesandStructuresGroup -.-> go/strings("`Strings`") go/DataTypesandStructuresGroup -.-> go/structs("`Structs`") go/ObjectOrientedProgrammingGroup -.-> go/struct_embedding("`Struct Embedding`") subgraph Lab Skills go/variables -.-> lab-149097{{"`Defining and Using Structures in C`"}} go/functions -.-> lab-149097{{"`Defining and Using Structures in C`"}} go/strings -.-> lab-149097{{"`Defining and Using Structures in C`"}} go/structs -.-> lab-149097{{"`Defining and Using Structures in C`"}} go/struct_embedding -.-> lab-149097{{"`Defining and Using Structures in C`"}} 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 cannot be duplicated within the same package.
  • The field names cannot be duplicated 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 type are the same, 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:

package main

import "fmt"

type Store struct {
    productName string
    productType string
    price       int
}

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

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

After running, the following result is displayed:

lan1:
Drinks
Coca-Cola
3

In this program, we instantiated a convenience store using var and then assigned it to this instance using ..

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)
}

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() {
    lan2 := new(Store)
    // Use %T to output the type
    fmt.Printf("Type of lan2: %T\n", lan2)

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

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

The result is as follows:

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

When using the new keyword for instantiation, the "instance" it gets 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)
}

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)
}

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:

  • Structure is a compound type that can contain multiple different types of data.
  • The value of a structure is the zero value of the corresponding type when it is not assigned.
  • Three methods of instantiating a structure

In the next experiment, we will delve into more knowledge about structures.

Other Go Tutorials you may like