Welcome To Golang By Example

Executable and non-executable module in Go (Golang)

Module is a directory containing nested go packages. So essentially module can be treated as a package only which contains the nested package. Now package can be either executable package or utility package (non-executable). Similar to package, modules can be of two types.

Let’s see an example to understand both. We have to create a module that can be used by others (Non-Executable module or Utility Module) and a module(Executable module) that can import that 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.

So essentially