Open In App

Pointer to a Struct in Golang

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Pointers in Golang is a variable which is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system. You can also use a pointer to a struct. A struct in Golang is a user-defined type which allows to group/combine items of possibly different types into a single type. To use pointer to a struct, you can use & operator i.e. address operator. Golang allows the programmers to access the fields of a structure using the pointers without any dereferencing explicitly. 

Example 1: Here, we are creating a structure named Employee which has two variables. In the main function, create the instance of the struct i.e. emp. After that, you can pass the address of the struct to the pointer which represents the pointer to struct concept. There is no need to use dereferencing explicitly as it will give the same result as you can see in the below program (two times ABC). 

Go




// Golang program to illustrate the
// concept of the Pointer to struct
package main
 
import "fmt"
 
// taking a structure
type Employee struct {
 
    // taking variables
    name  string
    empid int
}
 
// Main Function
func main() {
 
    // creating the instance of the
    // Employee struct type
    emp := Employee{"ABC", 19078}
 
    // Here, it is the pointer to the struct
    pts := &emp
 
    fmt.Println(pts)
 
    // accessing the struct fields(liem employee's name)
    // using a pointer but here we are not using
    // dereferencing explicitly
    fmt.Println(pts.name)
 
    // same as above by explicitly using
    // dereferencing concept
    // means the result will be the same
    fmt.Println((*pts).name)
 
}


Output:

&{ABC 19078}
ABC
ABC

Example 2: You can also modify the values of the structure members or structure literals by using the pointer as shown below: 

Go




// Golang program to illustrate the
// concept of the Pointer to struct
package main
 
import "fmt"
 
// taking a structure
type Employee struct {
 
    // taking variables
    name  string
    empid int
}
 
// Main Function
func main() {
 
    // creating the instance of the
    // Employee struct type
    emp := Employee{"ABC", 19078}
 
    // Here, it is the pointer to the struct
    pts := &emp
 
    // displaying the values
    fmt.Println(pts)
 
    // updating the value of name
    pts.name = "XYZ"
 
    fmt.Println(pts)
 
}


Output:

&{ABC 19078}
&{XYZ 19078}


Last Updated : 09 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads