0
0
GoHow-ToBeginner · 3 min read

How to Use Replace Directive in go.mod for Go Modules

The replace directive in go.mod lets you override a module path with another module or local directory. It is useful for testing local changes or using a different version without changing the original dependency. You add it by specifying replace old => new in your go.mod file.
📐

Syntax

The replace directive has this form in go.mod:

  • replace <old-module-path> [old-version] => <new-module-path> [new-version]

Here:

  • old-module-path: The module path you want to replace.
  • old-version (optional): The version of the old module to replace.
  • new-module-path: The module path or local directory to use instead.
  • new-version (optional): The version of the new module.

If you omit versions, the replacement applies to all versions of the old module.

go
replace example.com/old/module => ../local/module
💻

Example

This example shows how to replace a remote module with a local copy for testing changes:

go
module example.com/myapp

go 1.20

require example.com/old/module v1.2.3

replace example.com/old/module => ../local/module
⚠️

Common Pitfalls

Common mistakes when using replace include:

  • Using incorrect paths or versions, causing build errors.
  • Forgetting to remove replace before publishing, which can cause unexpected dependencies.
  • Replacing modules with incompatible versions or code, leading to runtime errors.

Always verify the replacement path exists and matches the expected module structure.

go
/* Wrong usage: missing '=>' or wrong syntax */
replace example.com/old/module ../local/module

/* Correct usage */
replace example.com/old/module => ../local/module
📊

Quick Reference

DirectiveDescriptionExample
replaceOverrides a module path or versionreplace example.com/old => ../local
old-module-pathModule to replaceexample.com/old/module
new-module-pathReplacement module or local path../local/module
version (optional)Specify version to replace or usev1.2.3

Key Takeaways

Use the replace directive in go.mod to override module paths or versions easily.
You can replace a remote module with a local directory for testing changes.
Always check paths and versions carefully to avoid build or runtime errors.
Remove replace directives before publishing your module to avoid dependency issues.