Go Modules And Sub-Packages

849 views
Skip to first unread message

Kaveh Shahbazian

unread,
Jan 27, 2019, 3:06:50 PM1/27/19
to golang-nuts
How do you use Go modules with sub-packages? Do you use relative path for them? If you use replace directive in go.mod file, how do you manage the version?

Example:
.../github.com/user/package1
.../github.com/user/package1/package2
.../github.com/user/package1/package3
.../github.com/user/package1/package3/package4

And package4 is used by package2 and package3. And package2 and package3 is used by package1.

Jan Mercl

unread,
Jan 27, 2019, 3:52:26 PM1/27/19
to Kaveh Shahbazian, golang-nuts
On Sun, Jan 27, 2019 at 9:07 PM Kaveh Shahbazian <kaveh.sh...@gmail.com> wrote:

> How do you use Go modules with sub-packages? 

Honest question, what do you mean by sub-package?

Given package import paths like, for example


and


package a is free to import package b. And package b is equally free to import package a. Only it cannot happen simultaneously, that would be a circular import.

--

-j

Kaveh Shahbazian

unread,
Jan 27, 2019, 4:25:11 PM1/27/19
to golang-nuts
Honest question, what do you mean by sub-package?
I do not know what is the official phrase here. But to me the example is quite clear.

To break it down further, assuming the module is at version 3.1.9, how should we import package2 inside package1?

For example should the import path be github.com/user/package1/package2 or github.com/user/package1/v3/package2 or ./package2?

thepud...@gmail.com

unread,
Jan 27, 2019, 5:54:12 PM1/27/19
to golang-nuts
Assuming your repository is “github.com/user/package1”, your module is already on v3.1.9, you have a single go.mod file, and the go.mod file is in the root of the repository, then that would mean the first line in your go.mod file typically would be:

module github.com/user/package1/v3

To import package2 from code in package1, it would then be the following import statement:

import "github.com/user/package1/v3/package2"

In other words, your middle option, I think.

You can see more here, for example:

https://golang.org/cmd/go/#hdr-Module_compatibility_and_semantic_versioning

...which includes:

“In semantic versioning, changing the major version number indicates a lack of backwards compatibility with earlier versions. To preserve import compatibility, the go command requires that modules with major version v2 or later use a module path with that major version as the final element. For example, version v2.0.0 of example.com/m must instead use module path example.com/m/v2, and packages in that module would use that path as their import path prefix, as in example.com/m/v2/sub/pkg. Including the major version number in the module path and import paths in this way is called semantic import versioning”

Reply all
Reply to author
Forward
0 new messages