douquan9826 2016-04-15 04:14
浏览 49
已采纳

编译期间包中的未定义变量

I have two files within one package named db, one of which has a few unexported variables defined. Another one is a test file and would need to use these variables like so:

(This is the structure of the project)

$GOPATH/src/gitlab.com/myname/projectdir   
├── main.go
└── db
    ├── add.go
    └── add_test.go

(Here is a terse variation of the files)

db/add.go

package db

func Add(x, y int) int {
    return x + y
}

// some other functions that use a and b from `add_test.go`

db/add_test.go

package db

import (
    "testing"
)

var (
    a = 1
    b = 2
)

// test function use variables from add.go
func testAdd(t *testing.T) {
    result := add(a, b)
    if result != 3 {
        t.Error(err)
    }
}

Running go test within db/ directory passed, but once I ran go run main go it produced the following error:

db/add.go:: undefined: a
db/add.go:: undefined: b

Seems like add.go cannot find a and b from add_test.go during the build.

main.go

package main

import (
    "fmt"
    "gitlab.com/myname/projectdir/db"
)

func main() {
    res := db.Add(1, 2)
    fmt.Println(res)
}

Is this because add_test.go is not included during the build?

  • 写回答

3条回答 默认 最新

  • douye2110 2016-04-15 06:47
    关注

    This is just the way how go tool works.

    _test.go files are compiled only when you run go test. When a package is imported from another package any code from its _test.go files is not used.

    Try running go build or go install from inside db package. It will fail.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块
  • ¥15 nhanes加权logistic回归,svyglm函数