英文:
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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论