为了账号安全,请及时绑定邮箱和手机立即绑定

当从 Golang 中的另一个包调用时,全局变量变为 nil

当从 Golang 中的另一个包调用时,全局变量变为 nil

Go
蝴蝶不菲 2022-06-01 18:12:57
repo/common/logger.gopackage commonvar once sync.Oncevar Logger *logrus.Loggerfunc InitLogger() {   once.Do(func() {        Logger = logrus.New()        Logger.Out = filename // file opened and *file assigned here for logging    })    return Logger}回购/setup_test.gopackage mainfunc setUp() {    common.InitLogger()    fmt.Println(common.Logger) // prints some pointer related things which means logger is initialized}func TestMain(m *testing.M) {    fmt.Println("Starting Test...")    setUp()    code := m.Run()    common.APILog.Println("Finishing Main...")    os.Exit(code)}回购/车辆/品牌/maruti/car/mycar_test.gopackage carfunc TestMyFunc(t *testing.T) {    **t.Log(common.Logger)               // When i run go test ./... this Prints nil , Why ?**    // Doing some tests}由于这个 common.Logger.Println("some data") 到处都给出零指针错误根据我的理解,一旦 Logger 被初始化,它应该是可用的,因为它是一个全局变量。我肯定在这里遗漏了一些微妙的东西。请帮忙
查看完整描述

1 回答

?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

每个包都经过独立测试。的测试main有一个TestMain调用setUp. 测试car没有,因此在测试该包时变量未初始化。



查看完整回答
反对 回复 2022-06-01
  • 1 回答
  • 0 关注
  • 282 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号