Go local modules

Following the steps outlined in the below doc did not work with 1.21.

All help appreciated.

I just tried it on 1.21.1 and works for me.
Your link points to the middle of a tutorial. Have you checked the previous section where they make the greetings-module?

Anyhow, this what you end up with:

.
├── greetings
│  ├── go.mod           // defaults of this file 
│  │                    // (created by go mod init) are good
│  └── greetings.go     // package greetings AKA a library/module
└── hello
   ├── go.mod          // uses a replace-directive that tells go-code
   │                   // in this package where "example.com/greetings" 
   │                   // can be found locally in stead of online
   └── hello.go        // package main AKA an executable with a main-func

Here are the steps I did:

  1. make empty new work-directory work
  2. make directory for greetings-module work/greetings (package greetings)
  3. run go mod init example.com/greetings in this directory. This creates a go.mod file for this module.
  4. paste code to work/greetings/greetings.go
  5. make directory for hello-module work/hello/ (package main)
  6. run go mod init example.com/hello in this directory. Again a go.mod file is made.
  7. edit work/greetings/go.mod so that it considers every import to example.com/greetings that it finds in code, to actually use ../greetings (this was new for me, it’s very cool that this is possible, before I was just editing my .go-code but apparently you can redirect with the go.mod-file. VERY COOL)
  8. run go run hello.go in work/hello. The (quite amazing) go build system will do all the rest.

For step 7, it was new for me that we can use go mod edit to (more safely) edit the go.mod-file. I had done some manual editing of that file in the past but it was quite interesting to read go help mod edit.

For reference, this is what my hello/go.mod file looks like after the command.

> go mod edit -replace example.com/greetings=../greetings

module example.com/hello

go 1.21.1

replace example.com/greetings => ../greetings

require example.com/greetings v0.0.0-00010101000000-000000000000

Thanks. But according to the tutorial we are supposed to change the calling module hello.
From the command prompt in the hello directory, run the following command:

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

Yes, we are changing work/hello/go.mod. As you can see in my code fragment of go.mod on the first line, this is the module we are changing.

The replace-statements basically take care of changing import "example.com/greetings" in hello.go on the fly to import "../greetings". Manually changing the imports in hello.go like that, would be an alternative solution but I think it’s nice that go mod supports this replace-mechanism.

Thanks for the help.

No problem. It was nice discovering this functionality of go mod.

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