Intro to Modules on Go - Part 1

What are Go modules?

Starting from Go 1.11 'modules' have been introduced to ease / formalize code sharing between Go projects much like other mainstream languages.

Go Modules are very handy way to contain the code into distributable units.

We declare a project as module by using the go mod command. This modules

created can be included as "dependency".

Writing a Go Module

Lets write a module which doubles a number. A Go module is nothing but a simple Go project but that resides outside your $GOPATH . Go modules are initialized in project

with the go mod command. Let create a dir called localmod1 outside $GOPATH

and init module with the command

mkdir localmod1

cd localmod1

go mod init localmod1

This above step creates a go.mod file. It has the below contents.

module localmod1 go 1.12

Create a file called localmod1.go now and put the below code.

package localmod1 import ( "fmt" ) func DblX(x int) int { fmt.Printf("dboubling %v", x) return x * 2 }

now our module is ready with some real code. Next step is to consume it so that we prepare it for other modules to use them.

Using published module in another Go module

Modules can be consumed in two ways either from local or directly from github. Though the latter is the most recommended however, on some cases it make sense (and useful) to treat as if they are published locally.

Lets create another module say usingmod1 which uses localmod1 .

mkdir usingmod1

cd usingmod1

go mod init usingmod1

like before the above step creates a empty go.mod file as shown below

module usingmod1 go 1.12

local

Now lets use the 'localmod1' by adding it as a dependency. Since localmod1 is still in our local but we can assume that its been published to github thereby creating an alias pointing to location of localmod1 absolute path. Add the following lines to go.mod

require github.com/prassee/localmod1 v0.0.0 replace github.com/prassee/localmod1 => ../localmod1

here the git repo github.com/prassee/localmod1 is an imaginary or yet to create location. After adding lets run go mod tidy command to let go to formalize our dependency definition. The upadted version look like below.

module usingmod1 replace github.com/prassee/localmod1 => ../localmod1 go 1.12 require github.com/prassee/localmod1 v0.0.0-00010101000000-000000000000 // indirect

Now we are all set to use the imported module in our code. In main.go add the following lines.

package main import ( "fmt" "github.com/prassee/localmod1" ) func main() { fmt.Printf("using mod1") localmod1.DblX(23) }

Thats for now. In the next part we can explore how to publish a module in to Github .

until then enjoy Go modules ...

References

Iam still picking up Go here are the references I've used to learn myself writing Go modules.