Dereferencing a pointer from another package

This example aims to demonstrate declaration of a pointer and accessing the value of the variable which the pointer points to.

The following will be the directory structure of our application.
├── parent
│   ├── go.mod
│   ├── main.go
│   └── child
│       └── child.go

Go inside the parent directory and run the following command to create a go module named parent.

go mod init parent

The above command will create a file named go.mod. The following will be the contents of the file.

module parent

go 1.14

parent\main.go
package main

import (
	"fmt"
	c "parent/child"
)

func main() {
	a := &c.Data
	fmt.Println("Address of Data is", a)
	fmt.Println("Value of Data is", *a)
	*a++
	c.PrintData()
}

We are aliasing the child package as c. The & operator is used to get the address of a variable. In the main function, we are now able to access the address of the Data, using above alias. We deference a and print the value of it.


parent\child\child.go

Create a file child.go inside the child folder. The file inside the child folder should start with the line package child as it belongs to the child package.

package child

import "fmt"

var Data = 10

func PrintData() {
	fmt.Println("Value of Data is", Data)
}

parent>go run main.go

If you run the program, you will get the following output.

Address of Data is 0x563230
Value of Data is 10
Value of Data is 11


Most Helpful This Week