How to instantiate Struct Pointer Address Operator in Golang?

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to show how to instantiate
// Struct Pointer Address Operator
package main
  
import "fmt"
  
type shape struct {
    length  int
    breadth int
    color   string
}
  
func main() {
  
    // Passing all the parameters
    var shape1 = &shape{10, 20, "Green"}
  
    // Printing the value struct is holding
    fmt.Println(shape1)
  
    // Passing only length and color value
    var shape2 = &shape{}
    shape2.length = 10
    shape2.color = "Red"
  
    // Printing the value struct is holding
    fmt.Println(shape2)
  
    // Printing the length stored in the struct
    fmt.Println(shape2.length)
  
    // Printing the color stored in the struct
    fmt.Println(shape2.color)
  
    // Passing only address of the struct
    var shape3 = &shape{}
  
    // Passing the value through a pointer
    // in breadth field of the variable 
    // holding the struct address
    (*shape3).breadth = 10
  
    // Passing the value through a pointer
    // in color field of the variable
    // holding the struct address
    (*shape3).color = "Blue"
  
    // Prinitng the values stored
    // in the struct using pointer
    fmt.Println(shape3)
}

chevron_right


Output:

&{10 20 Green}
&{10 0 Red}
10
Red
&{0 10 Blue}



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.