Welcome To Golang By Example

Importing package from different module locally in Go (Golang)

There are cases when we want to import a module which is present locally. Let’s understand how we can import such module. But first, we have to create a module that can be used by others and then import it into the other module. For that let’s create two modules

school module will be calling code of the sample.com/math module

Let’s first create the sample.com/math module which will be used by school module

go mod init sample.com/math
package math

func Add(a, b int) int {
	return a + b
}

Now let’s create the school module

go mod init school
module school

go 1.14

replace sample.com/math => ../math
package main

import (
	"fmt"
	"sample.com/math"
)

func main() {
	fmt.Println(math.Add(2, 4))
}

Now do a go run

go run school.go

It is able to call the Add function of the sample.com/math  module and correctly gives the output as 6.

Also, it will update the go.mod with version information of the sample.com/math module

module school

go 1.14

replace sample.com/math => ../math

require sample.com/math v0.0.0-00010101000000-000000000000