How to instantiate Struct Pointer Address Operator in Golang?
Last Updated :
20 Aug, 2021
As pointers are the special variables that are used to store the memory address of another variable whereas, the struct is user-defined data type that consists of different types. A struct is mainly a holder for all other data types. By using a pointer to a struct we can easily manipulate/access the data assigned to a struct. To use pointer to a struct we use “&” i.e, address operator. In Go lang, by using pointers to a struct we can access the fields of a struct without de-referencing them explicitly.
Example: Here we have defined one struct names as “shape” and we are passing the values to the field of this struct. Also, we are printing the value of the struct using pointers.
Go
package main
import "fmt"
type shape struct {
length int
breadth int
color string
}
func main() {
var shape1 = &shape{ 10 , 20 , "Green" }
fmt.Println(shape1)
var shape2 = &shape{}
shape2.length = 10
shape2.color = "Red"
fmt.Println(shape2)
fmt.Println(shape2.length)
fmt.Println(shape2.color)
var shape3 = &shape{}
(*shape3).breadth = 10
(*shape3).color = "Blue"
fmt.Println(shape3)
}
|
Output:
&{10 20 Green}
&{10 0 Red}
10
Red
&{0 10 Blue}
Share your thoughts in the comments
Please Login to comment...