liveBook · Manning

Go mod edit -replace

As explained in Learn Go with Pocket-Sized Projects

A module replacement is a Go module configuration that makes dependency resolution use an alternate module path or local directory, optionally at a specified version.

go mod edit -replace changes where Go resolves a module dependency. It can select a different version, branch, or tag, or point a module path to a local implementation. section 11.1.3 section 11.6

Use the command in these forms:

  • go mod edit -replace=old_module=new_module replaces one module path with another. section 11.1.3
  • go mod edit -replace=github.com/stretchr/testify=../stretchr/testify points a dependency at a local clone; absolute paths also work. section 11.1.3
  • go mod edit -replace=github.com/moby/moby=github.com/moby/moby@dev selects a branch, tag, or version reference. section 11.1.3

Use an unpublished local module

Suppose the module learngo-pockets/habits exists locally at ../10-habits/7_track. Run go mod edit -replace=learngo-pockets/habits=../10-habits/7_track. The command adds replace learngo-pockets/habits => ../10-habits/7_track to go.mod, allowing imports such as the module's api package. section 11.1.3

A replacement targets the module directory, not an individual package or .go file. Directly importing ../habits/api fails in module mode, and an unpublished path without a dotted host component can produce a malformed module-path error. section 11.1.3

Local replacements are useful for development but can make a project difficult to share because collaborators may not have the same directory. Publishing modules under a domain-prefixed path usually gives the Go toolchain a retrievable dependency. section 11.1.3

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains command syntax, module-versus-package paths, generated go.mod output, and sharing limitations without detailing resolver internals.
Examples
Demonstrates local testify and habits modules, a development branch of moby, generated go.mod output, and failed import commands.
What it assumes
Assumes familiarity with Go imports and modules while clarifying module paths, packages, local directories, and go.mod directives.
What you can do after
Operate/configure Go modules with go mod edit -replace for local dependencies or selected library versions.
How it connects
Connects module replacement with Go modules, go.mod, dependency resolution, local implementations, and version references.

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.