Go.work: which module uses which folder

Hi forum,

In the replace way, there’s a one-to-one mapping relationship, for example, the module example.com/hello is mapped to folder …/hello

$ go mod edit -replace example.com/hello=../hello

go.mod:
replace example.com/hello => ../hello 

But in the new multi-module workspaces way, there’s no such mapping. How can one figure out who’s using the folder ./hello ?

go.work:
use ./hello

Isn’t it better to spell out the mapping relationship too, like this:

example.com/hello => ./hello 

Thanks

Hi @ljh,

The module in ./hello has a mod file with a module path in it.

Whenever the main module (that is, the module where you invoke the Go commands) has a go.work file, then every import path that matches the module path in ./hello/go.mod will be redirected to the local module.

Example:

go.work in the main module:

use ./hello

.hello/go.mod:

module git.hoster/my/repository

main.go:

import "git.hoster/my/repository"

Here, the import path matches the module path of the local module in ./hello, and the Go commands will use this local module instead of the remote one.

(Disclaimer: Written at 10:30pm on a mobile - all errors are mine.)

2 Likes

Thanks Christoph,

What if I have multiple repos / modules

example.com/hello1
example.com/hello2
example.com/hello3
example1.com/hello
example2.com/hello
example3.com/hello

and multiple folders

./hello1
./hello2
./hello3

That works as well. Each local module is unambiguously identified by its module path go. mod

Thanks Christoph,

But the go.mod does not have the replace line:

replace example.com/hello => ../hello 

With the go.work style, it only has the require lines.

module main

go 1.18

require example1.com/hello v1.0.0
require example2.com/hello v1.0.0
require example3.com/hello v1.0.0

How do I know which repo / module above, is linked to the ./hello below?

go.work:
use ./hello

Thanks.

I think I may get it.

If there’s go.work, the import example.com/module will try those local directories in go.work first. If not found, it will try online repositories. And module names like this example.com/module, github.com/golang/glog, etc. are unique, so there will be no ambiguous. Am I thinking right?

Yes, this summarizes it well.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.