英文:
Declaring a struct in a separate golang package cannot return value, but it can when declared specifically
问题
尝试从另一个包中导入一个结构类型,它可以完美地返回,但是除非在不使用实例化函数的情况下声明,否则无法找到该结构的值。
// X 执行并正常找到值,Z 不行。
package main
import (
"fmt"
"github.com/example/command"
)
func main() {
x := &command.Command{}
z := command.NewCommand()
fmt.Println(x.command)
fmt.Println(z.command)
}
package command
type Command struct {
// Command 的结构化数据/对象
alias string
command string
verbose bool
}
func NewCommand() *Command {
// 为 []Command 对象创建一个新的容器
return &Command{"", "", false}
}
我在这里漏掉了什么...?
英文:
Trying to import a struct type from another package, and it returns perfectly, but the values of that struct can't be found unless declared without the use of an instantiation function.
// X executes and finds values fine, Z does not.
package main
func main () {
x := &Command{}
z := command.NewCommand()
fmt.Println(x.command)
fmt.Println(z.command)
}
package command
type Command struct {
// Our structured data/object for Command
alias string
command string
verbose bool
}
func NewCommand() *Command {
// Creates a new container for []Command objects
return &Command{"","",false}
}
What exactly am I missing here...?
答案1
得分: 2
你的结构字段需要大写才能在包外访问。
type Command struct {
// Command 的结构化数据/对象
Alias string
Command string
Verbose bool
}
英文:
Your struct fields needs to be capital for it to accessible outside the package.
type Command struct {
// Our structured data/object for Command
Alias string
Command string
Verbose bool
}
答案2
得分: 1
相关的golang规范如下:
为了允许从另一个包中访问,标识符可以被导出。如果满足以下两个条件,则标识符被导出:
标识符名称的第一个字符是一个Unicode大写字母(Unicode类“Lu”);并且标识符在包块中声明,或者是字段名或方法名。其他所有标识符都不会被导出。
由于您的结构体字段没有大写字母开头,它们不符合被导出到另一个包的条件。为了解决这个问题,您需要将希望在外部访问的字段首字母大写。
可能会像这样:
type Command struct {
Alias string
Command string
Verbose bool
}
英文:
The relevant golang spec is:
> An identifier may be exported to permit access to it from another
> package. An identifier is exported if both:
>
> the first character of the identifier's name is a Unicode upper case
> letter (Unicode class "Lu"); and the identifier is declared in the
> package block or it is a field name or method name. All other
> identifiers are not exported.
Since your struct fields are not capitalized, they do not qualify to be exported to another package. In order to fix this, you need to capitalize the fields you would like to access externally.
It might look something like this:
type Command struct {
Alias string
Command string
Verbose bool
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论