【问题标题】:Golang compilation error: undefined private function "findCluster" in exported functionGolang编译错误:导出函数中未定义的私有函数“findCluster”
【发布时间】:2020-02-27 10:56:56
【问题描述】:

我在项目A下的包test/api中写了以下代码:

func ListClusterTestCase() {
    ...
    getResponse, err = ocm.Connection.Get().
        Path(ClustersEndpoint).
        Parameter("order", "creation_timestamp desc").
        Send()
    getResult := ReadResponse(getResponse, err, 200)
    clusters := GetClusters(getResult)
    Expect(findCluster(clusters, clusterID)).To(BeTrue()) // <-- private function defined in a different file in test/api (called clusters_test.go)
}

...

func ProbeTests() []*ocm.TestCase {
    tc := []*ocm.TestCase{}
    ...
    tc = append(tc, ListClustersTestCase(cfg)...)
    return tc
}

另一个项目中的一个文件——项目B——导入这个test/api包试图引用ProbeTests

import (
    cms "my/project/test/api"
)


func AddTests(cfg *ocm.TestConfig) {
    ...
    ocm.AddTestCases(cms.ProbeTests(cfg))
}

我在尝试编译项目 B 时遇到以下编译错误:

../../go/pkg/mod/.../test/api/clusters_load_test_cases.go:59:12: undefined: findCluster

为什么我的项目无法编译?为什么不编译整个包test/api?它只编译包含导出的ListClusterTestCase 的文件吗?当我编译项目 A 时,它工作得很好。

【问题讨论】:

  • findCluster 声明在哪个文件中?
  • 该包中的一个单独文件(称为clusters_test.go
  • 测试文件,那些以_test.go 结尾的文件不包含在非测试导入的二进制文件或包中。将其移至非测试文件。
  • 明白了,谢谢!能否请您写在答案中,以便我给您答案?

标签: go import package


【解决方案1】:

如果您不希望在导入包时省略 findCluster 声明,则需要将其移动到非测试文件中。

编译包时,build 会忽略以 '_test.go' 结尾的文件。

https://golang.org/cmd/go/#hdr-Compile_packages_and_dependencies

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多