How do I resolve “cannot find module for path X” importing a local Go module?

淺唱寂寞╮ 提交于 2019-11-28 08:48:24
Hamza Anis

So you wrote a Go "library" module which:

  • you don't want to publish on GitHub or elsewhere
  • you want to import and use it in your project (the "main" module).

Use the replace directive to solve this problem.

Given the module name "X" as you've called it, in your main module add the following lines:

require "X" v0.0.0
replace "X" v0.0.0 => "{local path to the X module}"

The path should point to the root directory of the module, and can be absolute or relative.

To import package util from module X:

import "X/util"

(You don't import modules. You import packages from modules.)


Explanation

Go's module functionality is designed for publicly published modules. Normally, a module's name is both its unique identifier and the path to its public repo. When your go.mod declares a module dependency with the require directive, Go will automatically find and retrieve the specified version of the module at that path.

(See also in the Go Modules FAQ, Can I work entirely outside of VCS on my local filesystem?)

If, for example, your go.mod file contains require github.com/some/dependency v1.2.3, Go will retrieve the module from GitHub at that path. But if it contains require X v0.0.0, "X" isn't an actual path and you will get the error cannot find module for path X.

The replace directive allows you to specify a replacement path for a given module identifier and version. There are many reasons you'd want to do this, such as to test changes to a module before pushing them to the public repo. But you can also use it to bind a module identifier to local code you don't ever intend to publish.

Hope this helps.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!