Declaring a struct in a separate golang package cannot return value, but it can when declared specifically

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

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
}

huangapple
  • 本文由 发表于 2017年1月26日 09:47:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/41864716.html
匿名

发表评论

匿名网友

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

确定