CodeGym /课程 /Go SELF /replace: local replacements, risks, and when it is approp...

replace: local replacements, risks, and when it is appropriate

Go SELF
第 35 级, 课程 2
可用

1. Why replace is needed: “I want to check a fix, but there is no release”

Imagine a typical situation from real-world development: you found a bug in a library you use, and you have already written a fix. But the fix has not been published yet (there is no version tag, no release, and sometimes you do not even have permission to push to the repository). You want to build and run your application with a local fix right now, without changing imports across the codebase and without turning the project into a manual pile of ZIP archives like “dependencies_final_final2.zip”.

This is where replace appears: it is a mechanism that tells Go tools something like this: “when you see a module with this module path, take it not from where you usually do, but from here.” Important: this is a dependency resolution rule, not a change to your source code.

What replace does and does not do

When you first see replace, it is tempting to think of it as a “magic button: download me another version.” But this is not downloading or installing — it is reassigning the source.

To be precise, replace affects where from the go tools will take a module’s source code when they build your main module. In other words, replace lives “at the edge of the project”, next to your require entries, and affects builds and tests, not the syntax of Go itself.

It is also useful to remember that Go tools are strongly oriented toward predictability and determinism. That is why they like to pin versions and checksums. replace, however, is like a “service entrance”: it is allowed, but you must use it carefully, because it can easily make your build depend on your local machine (and your local machine is a creative thing: today it is one way, tomorrow it is “oops, I reinstalled the system”).

2. replace syntax: two main forms

Now comes an important point: we will look at replace not as theory, but as text in go.mod that you will actually see in a PR diff.

Replacement to a local path

This form is used when you have a folder with another module on disk (that is, it contains its own go.mod), and you want to temporarily use it instead of the normally downloaded dependency.

// go.mod (your main module)
module example.com/todoapp

go 1.25

require example.com/todolib v0.1.0

replace example.com/todolib => ../todolib

Here it is important to notice two nuances right away.

The first nuance is that replace points to the module root, not to a package subfolder. In other words, ../todolib must be the directory where ../todolib/go.mod lives.

The second nuance is that the path ../todolib is interpreted relative to the folder where go.mod is located, not relative to where you launch your IDE or go test.

Replacement to another module path and version

This form appears when you use a fork of a dependency or an alternative source, but want to keep the imports in the code unchanged.

In schematic form, it may look like this:

replace example.com/todolib => example.com/todolib-fork v0.1.1

The idea: in the code you still write import "example.com/todolib/task", but in practice Go will take the module from a different place. Yes, it is a bit like “switching the supplier on the invoice”, but the boxes in the warehouse are still labeled with the old name.

3. Practical scenario: a shared module and connecting it through replace

So that replace does not remain an abstract scare story, let us play through a simple and very realistic situation. We have a learning application called todoapp. We want to extract part of the code into a small library called todolib so that we can reuse types and functions in another project (for example, in a separate utility or in future experiments). But we are not going to publish the library “to the internet” — we will just put it next to the project on disk and connect it through replace.

Directory structure

It is important to picture the files in your head. Imagine this structure:

workspace/
  todolib/
    go.mod
    task/
      id.go
    title/
      normalize.go

  todoapp/
    go.mod
    main.go

Pay attention: these are two different modules, because each folder has its own go.mod. This independence is exactly what makes replace possible and meaningful.

A minimal todolib: the ID type

Let us make a tiny task package in the todolib module.

package task

// ID — task identifier.
// For now it is just an int, but the type helps avoid mixing it up with other numbers.
type ID int

Here we are not doing anything “clever”: we are simply introducing a type. In practice, this improves readability and reduces the chance of confusing a “task id” with a “number of tasks” (both are int, but the meaning is different).

Another small title package: title normalization

Let us add a utility for titles. For now it only trims spaces (we are not declaring war on all spaces in the universe).

package title

import "strings"

// Normalize trims the title to a neat form.
func Normalize(s string) string {
	return strings.TrimSpace(s)
}

Using todolib in todoapp as an external dependency

Now in todoapp/main.go we import the packages from todolib by module path.

package main

import (
	"fmt"

	"example.com/todolib/task"
	"example.com/todolib/title"
)

func main() {
	var id task.ID = 1
	fmt.Println("id =", id)                           // id = 1
	fmt.Println(title.Normalize("   buy milk   "))    // buy milk
}

Notice an important thing: the imports look like imports of a real external library. That is the convenience: when you later decide to publish todolib or connect it without replace, you will not need to rewrite the todoapp code.

Connect the local module through replace

Now the key point: in todoapp/go.mod we pin the dependency and swap its source.

module example.com/todoapp

go 1.25

require example.com/todolib v0.0.0

replace example.com/todolib => ../todolib

Why version v0.0.0? Because in this scenario the version is not that important: we are taking the code from a local folder anyway. In “real” projects people usually still try to have proper versions, but for learning and local development this entry helps you understand the mechanism.

4. Risks of replace: how to turn a project into “works only on my machine”

Now comes a bit of “build engineer nitpicking”, but without it replace becomes a trap. The main risk is very simple: replace easily breaks reproducibility.

If you made replace ... => ../todolib, then your project now depends on another developer having a folder called ../todolib in exactly the same place. On CI (where the repository is usually cloned into a clean directory), that folder will not exist. And the build will fail.

Moreover, if you accidentally committed such a replace into the repository, it is as if you glued a note to the project: “builds only on my laptop, because I have another repository sitting next to it.” This is not always evil (sometimes people do this intentionally in monorepos), but it definitely requires discipline.

There is also a more subtle risk: when you use go install some/tool@version, Go deliberately avoids ambiguities and imposes restrictions on what can be in go.mod. In particular, in some scenarios replace simply cannot be used, so that the build of a specific tool version remains unambiguous.

And one more practical observation: Go tools often behave “like adults” — instead of quietly fixing something, they raise an error and explicitly tell you which command to run. It is useful to remember this, because with incorrect dependencies you will see hints like “no required module provides package ...; to add it: go get ...”.

5. When replace is appropriate

So that you do not leave with the feeling “wait, is this forbidden magic?”, let us formulate a healthy position. replace is a normal tool. It is just not for everyday “this is more convenient”, but for specific working situations.

  • replace is appropriate when you are actively developing a library and an application at the same time, but the library is not yet ready for publication. Historically, this was one of the typical ways to “connect local unpublished changes”, and after publishing you had to remember to remove replace, otherwise the project became hard to move around.
  • replace can be appropriate when you use a dependency fork (for example, you need an urgent fix). Then you can temporarily replace the module with the fork, and later return to the official one.
  • replace is appropriate as a “repair mode” when the outside world is temporarily unavailable (for example, you are working in an isolated environment). But this is a rather rare story, and it is better if it is explicitly documented.

Flowchart: do we need replace?

Sometimes it is more useful to see the algorithm once than to read ten paragraphs (although we will still read them, because we are programmers).

flowchart TD
    A[Need to use a dependency] --> B{Is the required version available in the regular require?}
    B -->|Yes| C[Use require / go get]
    B -->|No| D{Are there local module changes?}
    D -->|Yes| E[Temporarily set replace to a local path]
    D -->|No| F[Find another version/fork and point replace to another module path]
    E --> G{Time to push/release/merge?}
    G -->|Yes| H[Remove replace or make a proper library release]
    G -->|No| I[Keep replace locally, but remember CI]

The moral here is important: replace is almost always a temporary solution. If it becomes permanent, that should be a conscious architectural decision, not “oops, I forgot to remove the line”.

A small hygiene rule

If you use replace, try to leave at least a comment next to it, so that in a month you (or your colleague) do not wonder why the dependency comes from ../something.

In Go this looks normal:

replace example.com/todolib => ../todolib // local development of todolib

This is not “beauty for beauty’s sake”. It really saves hours of life.

Remark about alternatives

There is a workspace mechanism (go.work) that is specifically designed to make it easier to work with several modules at once without constantly editing go.mod. In official materials, it is explicitly contrasted with the old “manual replace for local unpublished changes”.

But within this lecture we keep the focus: today it is important for us to learn to read and understand replace, because you will definitely encounter it in other people’s projects — even if you use workspaces yourself.

6. Common mistakes when working with replace

Mistake #1: replace points to a package subfolder, not to the module root.
A very common confusion for beginners: “I need the task package, it lives in ../todolib/task, so replace should point there.” But replace works at the module level, and the module is defined by the go.mod file. Therefore the correct target is the directory where go.mod lives, and the packages are already inside it.

Mistake #2: accidentally committed a local replace and broke the build for everyone else.
This is a classic: everything works for you, you happily make a PR, and a colleague (or CI) gets an error saying the folder does not exist. The reason is that ../todolib is a detail of your filesystem. If replace is only needed locally, it usually should not live in the main branch.

Mistake #3: thinking replace “downloads” a dependency or “updates” it.
replace downloads nothing and updates nothing. It only changes the rule for “where to take the source code from.” As a result, you can end up in a strange situation: you think you are using v1.2.3, because that is what is written in require, but in fact the code is taken from a local folder. This is especially unpleasant when you debug bugs: you are looking at one version, but building another.

Mistake #4: forgetting to remove replace when the changes have already been published or are no longer needed.
Historically, this was a real pain: you made a local fix, connected it through replace, then published the module, but forgot to remove replace — and the project keeps pointing to local sources that others do not have. In the official materials about workspaces, this scenario is mentioned directly as a typical reason why people wanted a more convenient way to work with multiple modules.

Mistake #5: being surprised that some commands behave more strictly because of replace.
For example, there are scenarios where Go intentionally limits ambiguities when installing tools by an exact version, and replace is forbidden there. If you hit an unexpected “not allowed”, this is not Go taking a personal dislike to you, but an attempt to preserve deterministic behavior.

1
任务
Go SELF, 第 35 级, 课程 2
已锁定
相邻库
相邻库
1
任务
Go SELF, 第 35 级, 课程 2
已锁定
相对 replace
相对 replace
1
任务
Go SELF, 第 35 级, 课程 2
已锁定
使用 fork 进行替换
使用 fork 进行替换
评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION