23

just starting to learn about Go Modules. I have a question on importing local packages inside the same module. The example I am looking at is this repo:

https://github.com/Azure/azure-service-bus-go

The module is module github.com/Azure/azure-service-bus-go. There is a separate package inside that module, atom (but it's not a module itself). When files inside the main package import atom, they do it like this: import "github.com/Azure/azure-service-bus-go/atom" -- see queue_manager.go as an example.

What I do not quite understand -- how does GO know to look at the local atom package, as opposed to, say the one on Github? It seems confusing to me that something that is part of the module being modified is referenced by a remote/absolute URI. Is it guaranteed that if I modify the file on local disk and build I'm actually referencing the latest version as opposed to something already pushed?

As a toy exercise I tried to create a module with a non-existent Github URI and it did in fact appear that go mod tidy tried to look that up against Github, even though a local copy did in fact exist

Yana K.
  • 1,926
  • 4
  • 19
  • 27
  • 3
    Because of the go.mod file. The go.mod file contains the full name of the module, so the build system knows not to lookup packages in that module remotely. Run `go mod init` for your project. – Burak Serdar May 21 '20 at 17:21
  • 7
    [How to Write Go Code](https://golang.org/doc/code.html) walk you through an example module demonstrating how this works – JimB May 21 '20 at 17:28

2 Answers2

20

List item

  • A module is a collection of go packages.
  • A package is a directory of .go files. Using packages, you organize your code into reusable units.
  • We can add a module to go project or upgrade the module version.
Hamed Naeemaei
  • 8,052
  • 3
  • 37
  • 46
  • I like the structure shown, but I see herein some breaking point regarding to Learning Go by J.Bodner, cited "_While you can store more than one module in a repository, it isn’t encouraged. Everything within a module is versioned together. Maintaining two modules in one repository means tracking separate versions for two different projects in a single repository_" . Again I am coming from Node.js world to go, so I am still in a shadow of learning Golang good practices so I might be mistaken, what do you think @Hamed Naeemaei ? – projektorius96 Dec 15 '22 at 13:53
  • 1
    It's better to have a module per each repository – Hamed Naeemaei Jan 14 '23 at 10:37
8

The module directive in the go.mod file declares the import-path prefix for all of the packages within that module.

If you are just starting to learn about Go modules, the Create a Go module tutorial might be a good place to start.

bcmills
  • 4,391
  • 24
  • 34