English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang Basic Tutorial

Golang Control Statements

Golang Function & Method

Golang Struct

Golang Slice & Array

Golang String(String)

Golang Pointer

Golang Interface

Golang Concurrency

Golang Error

Golang Miscellaneous

Go Language Struct and Pointer

You can also use a pointer tostructpointer. In Golang, struct (struct) is a user-defined type that allows grouping/composing different types into a single type. To use a pointer to a struct, you can useOperators, i.e., the address operator. Golang allows programmers to access the fields of a struct without explicitly dereferencing.

Example 1:Here, we create a struct named Employee with two variables. In the main function, create an instance of the struct, namely emp, and then, you can pass the address of the struct to a pointer representing the concept of the struct. There is no need to explicitly use dereferencing, as it will give the same result as the following program (both ABC).

package main
import "fmt"
//Define the struct
type Employee struct {
    //Setting the field
    name string
    empid int
}
func main() {
    //Instance created
    //Employee struct type
    emp := Employee{"ABC", 19078}
    //Here, it is a pointer to a struct
    pts := &emp
    fmt.Println(pts)
    //Accessing the struct field (employee's name)
    //Using a pointer, but here we have not used explicit dereferencing
    fmt.Println(pts.name)
    //By explicitly using dereferencing
    //The result is the same as above
    fmt.Println((*pts).name)
}

Output:

&{ABC 19078}
ABC
ABC

Example 2:You can also use pointers, as shown below to modify the value of a struct member or a struct literal:

package main
import "fmt"
//Define the struct
type Employee struct {
    name string
    empid int
}
func main() {
    //Instance created
    //Employee struct type
    emp := Employee{"ABC", 19078}
    //Here, it is a pointer to a struct
    pts := &emp
    //Display the value
    fmt.Println(pts)
    //Update the value of name
    pts.name = "XYZ"
    fmt.Println(pts)
}

Output:

&{ABC 19078}
&{XYZ 19078}