从其他包导入Golang结构体。

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

golang struct from other package

问题

你在做的时候出错了。错误信息显示在结构字面量中的字段s是未知的。这是因为在Built_in结构体中,字段s的访问权限是私有的,无法从外部包访问。

要解决这个问题,你可以将s字段的访问权限更改为公共的。在base_structs.go文件中,将s字段的声明改为大写字母开头,这样它就可以从外部包访问了。修改后的代码如下:

package structs

type Built_in_func func([]string)

type Built_in struct {
    S string
    F Built_in_func
}

然后,在main.go文件中更新你的代码,使用大写字母开头的s字段:

var builtin_list []structs.Built_in

builtin_list = append(builtin_list, structs.Built_in{S: "exit", F: builtin.Exit})
builtin_list = append(builtin_list, structs.Built_in{S: "hi", F: builtin.Hi})

这样就可以解决你遇到的错误了。

英文:

Situation:

I've the following project structure:

root
    parser
       parser.go
    builtin
        exit.go
        hi.go
    structs
        base_structs.go
    main.go

.. and the base_structs.go file looks like this:

package structs

type Built_in_func func([] string)

type Built_in struct {
	s string
	f Built_in_func
}

I've imported the package in my main.go and I'm referencing the struct with structs.Built_in.

This is what I'm trying to do:

var builtin_list [] structs.Built_in

builtin_list = append(builtin_list, structs.Built_in{s:"exit", f:builtin.Exit})
builtin_list = append(builtin_list, structs.Built_in{s:"hi", f:builtin.Hi})

But I'm getting this error:

> unknown structs.Built_in field 's' in struct literal

Question:

What am I doing wrong?

答案1

得分: 14

在Go语言中,一个名称在包外的可见性取决于它的首字母是否大写。

所以,字段s实际上在包structs外部是不可见的,你会得到那个错误。

如果你像这样定义你的结构体(注意大写):

type Built_in struct {
    S string
    F Built_in_func
}

那么这将起作用(同样是大写):

structs.Built_in{S:"exit", F:builtin.Exit}

你可以在这里阅读更多信息:

https://golang.org/doc/effective_go.html#names

英文:

In Go, the visibility of a name outside a package is determined by whether its first character is upper case.

So the field s is actually not visible from outside the package structs and you get that error.

If you define your struct like (note the upper case):

type Built_in struct {
    S string
    F Built_in_func
}

Then this will work (again the upper case):

structs.Built_in{S:"exit", F:builtin.Exit}

You can read more here:

https://golang.org/doc/effective_go.html#names

huangapple
  • 本文由 发表于 2017年7月28日 09:27:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/45363448.html
匿名

发表评论

匿名网友

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

确定