Golang program to print pointer to a struct


In this article, we will write Golang programs to print pointer to a struct. A pointer stores the address of the memory location where the variable’s value is placed. We can the access the address of the variable using & operator. For ex= &a tell the address of the a.

Example 1

In this example, we will write a Golang program to show the pointer to a struct by creating a child struct and printing the pointer to that struct.

package main

import "fmt"

type Child struct {
   name string
   age  int
}

func main() {
   c := &Child{"Varun", 15}  
   fmt.Println("Pointer to struct is: ", c) 
}

Output

Pointer to struct:  &{Varun 15}

Example 2

In this particular example, we will write a Golang program to print pointer to a struct using the & operator which depicts the address.

package main
import "fmt"


type Child struct {
   name string
   age  int
}

func main() {
   c := Child{name: "Veronica", age: 10} 
   fmt.Printf("Pointer to struct is: %p\n", &c)  
}

Output

Pointer to struct is: 0xc0000b2018

Example 3: Golang Program to Print Pointer to Struct Using Person Struct

In this example, we will write a Golang program to print pointer to a struct using the Person struct. The pointer to the struct will be stored inside the variable and then printed on the console.

package main

import "fmt"

type Person struct {
   name string
   age  int
}

func main() {
   ps := Person{"Kalindi", 26}
   ptr := &ps 

   fmt.Printf("The Pointer to struct presented here is: %p\n", ptr)
}

Output

The Pointer to struct presented here is: 0xc000010030

Conclusion

We compiled and executed the program of referring pointer to a struct using three examples. In both of the examples we created a child struct but in the first example, we printed the pointer to the struct and in the second example, we printed the address of the pointer to the struct and in the third example we used a Person struct to execute program.

Updated on: 04-Apr-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements