How to import and alias package names?

Go also has the ability to alias package names. This example aims to demonstrate the importance of the use of alias package names in our Go programs.

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

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

go mod init vehicle

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

module vehicle

go 1.14

vehicle\main.go
package main

import (
	car1 "vehicle/car"
	car2 "vehicle/car"

	"fmt"
)

func main() {
	c1 := new(car1.Car)
	c1.Single(10)
	fmt.Println(c1.Price)

	c2 := new(car2.Car)
	c2.Double(10)
	fmt.Println(c2.Price)
}

We are aliasing the car package as car1 and car2. In the main() function, we are now able to create variables the c1 and c2 using above alias. We call the Single() and Double() method of the Car struct using c1.Single() and c2.Double().


vehicle\car\car.go

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

package car

type Car struct {
	Price int
}

func (obj *Car) Single(price int) int {
	obj.Price = price
	return obj.Price
}

func (obj *Car) Double(price int) int {
	obj.Price = price * 2
	return obj.Price
}

vehicle>go run main.go

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

10
20


Most Helpful This Week