How to access a struct from an external package in Go?

You will learn to create your own package and import your custom package. In this example, you will see how to import structure from another or child package. You will also be able to call functions of custom packages from the main package.

The following will be the directory structure of our application.
├── family
│   ├── go.mod
│   ├── main.go
│   └── father
│       └── father.go
│       └── son
│           └── son.go

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

go mod init family

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

module family

go 1.14

family\main.go

To use a custom package we must import it first. The import path is the name of the module appended by the subdirectory of the package and the package name. In our example the module name is family and the package father is in the father folder directly under family. And, the package son is in the son folder which is under father folder.

Hence, the line import "family/father" will import the father package, similary "family/father/son" will import the son package

package main

import (
	parent "family/father"
	child "family/father/son"

	"fmt"
)

func main() {
	f := new(parent.Father)
	fmt.Println(f.Data("Mr. Jeremy Maclin"))

	c := new(child.Son)
	fmt.Println(c.Data("Riley Maclin"))
}

We are aliasing the father package as parent and son package as child. In the main() function, we are now able to define the Father and Son struct using above alias.


family\father\father.go

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

package father

import "fmt"

func init() {
	fmt.Println("Father package initialized")
}

type Father struct {
	Name string
}

func (f Father) Data(name string) string {
	f.Name = "Father : " + name
	return f.Name
}

The init function can be used to perform initialization works and can also be used to confirm the correctness of the program before the execution begins.


family\father\son\son.go

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

package son

import "fmt"

func init() {
	fmt.Println("Son package initialized")
}

type Son struct {
	Name string
}

func (s Son) Data(name string) string {
	s.Name = "Son : " + name
	return s.Name
}

family>go run main.go

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

Father package initialized
Son package initialized
Father : Mr. Jeremy Maclin
Son : Riley Maclin


Most Helpful This Week