Wednesday, October 9, 2019

Using Go modules in separated local directories

Suppose I have a Go project, “foo”, which writes to the console. In this project, I have some .go files which have all the functions that actually write to the console.

Now I want to make these writing routines a separated module: “writer”, in another directory. I want two sibling directories: “foo” and “writer”. The “writer” will be used as a dependency within “foo”.

Within “writers” folder, run go mod init writer to create the go.mod file. Back in “foo”, edit its go.mod adding the new dependency:

module Foo

go 1.13.1

require (
  shoutergo v0.0.0
)

replace (
  shoutergo => ../shoutergo
)

The replace line will inform Go where to look for the module. Without it, Go will search in the internet, that’s why GitHub URLs work right away.

The version of the dependency, as far as I could find, is a Git tag, and to local modules it’s completely irrelevant, although necessary.

Now, in “foo”, we can import “writer” just like any other package:

import (
  "writer"
)

func main() {
  writer.SomeFunc()
}

As I keep learning Go and exploring the limits of the language, although I’m not entirely satisfied – lack of enums and namespaces –, I’m very pleased with its design choices with opted for simplicity. Feels like a better C.

No comments: