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条)

报告相同问题?

悬赏问题

  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题