如何调用在根包中声明的变量

huangapple go评论85阅读模式
英文:

How to call a variable declared on the root package

问题

我在根目录(MyPackage)下有一个version.go文件。

package MyPackage

var (
    Version = "undefined"
    Hash    = "undefined"
)

我还有第二个文件,位于MyPackage/cmd/bootloader/bootloader.go中。

package main

import (
    "MyPackage"
    "fmt"
)

func main() {
    fmt.Println(MyPackage.Version)
}

但是我得到了undeclared name: MyPackage"MyPackage" imported but not used as ext的错误,并且我不知道如何修复。

我尝试执行gotype bootloader.go,得到以下结果。

bootloader.go:9:14: undeclared name: MyPackage
bootloader.go:4:2: "MyPackage" imported but not used as ext

我将非常感谢任何提供帮助的人。

编辑:这与Golang全局变量访问不同,因为这将破坏变量的目的,因为我不想在每个main.go文件中重写它。我希望使用-ldflags来设置变量的值来构建main.go。

英文:

I have a version.go on my root folder(MyPackage).

package MyPackage
var (
    Version = "undifened"
    Hash = "undifined"
)

And I have second file found on MyPackage/cmd/bootloader/bootloader.go

package main
import(
       "MyPackage"
       "fmt"
)

func main() {
     fmt.Println(MyPackage.Version)
}

But I am gettingundeclared name: MyPackage and "MyPackage" imported but not used as ext on gotype and i dont know how to fix.

I tried executing this gotype bootloader.go and get this.

bootloader.go:9:14: undeclared name: MyPackage
bootloader.go:4:2: "MyPackage" imported but not used as ext

I will appreciate for any help will come.

Edit: This is not the same with Golang Global Variable access because this will defeat the purpose of that variables, because i don't want to rewrite it on the every main.go. because I want to build the main.go with the -ldflags to set the value on the variable.

答案1

得分: 2

如果有人遇到这个问题,可以在主包所在的目录上运行go install命令,这样gotype就不会继续输出错误信息了。

英文:

If someone have this, doing go install on the directory where the main package is, makes the gotype stop spitting the message.

huangapple
  • 本文由 发表于 2017年4月30日 19:55:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/43706088.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定