首页 > 解决方案 > 主模块和供应商目录提供的导入被标记为错误

问题描述

我想了解在复习 go 模块和供应商目录时遇到错误的原因。显然,在主模块和供应商文件夹中具有相同的包会导致错误,我想了解原因。据我了解,如果有一个go.mod go甚至不应该检查vendor文件夹的依赖关系。一旦我运行,go run ./main.go我会收到以下错误:

main.go:3:8: ambiguous import: found package test/testpkg in multiple directories:
        /Users/mic4ael/dev/mine/something-in-go/testpkg
        /Users/mic4ael/dev/mine/something-in-go/vendor/test/testpkg

go build -mod=mod但是,在用于构建二进制文件时不会发生这种情况。我会很感激解释为什么会这样。

GO111MODULE=""
$ tree
.
├── go.mod
├── main.go
├── test
├── testpkg
│   └── lib.go
└── vendor
    └── test
        └── testpkg
            └── lib.go

去.mod

module test

go 1.15

main.go

package main

import "test/testpkg"

func main() {
    testpkg.Echo("Test")
}

供应商/test/testpkg/lib.go

package testpkg

import "fmt"

func Echo(str string) {
    fmt.Printf("From vendored package %s\n", str)
}

testpkg/lib.go

package testpkg

import "fmt"

func Echo(str string) {
    fmt.Printf("From internal pkg: %s\n", str)
}

标签: gogo-modulesgovendor

解决方案


There are two packages with the same name, and that is the ambiguity. When you import test/testpkg it can be imported from the project itself or from the vendor directory.

Using go modules does not change the vendoring behavior. In fact, you can use go mod vendor to vendor modules locally. If a package appears under vendor/ it will be used from the vendored copy, otherwise it will be downloaded and used from the module cache. However, if you have a package in your project with the identical name as one of the packages under vendor, there is an ambiguity.


推荐阅读