2017-07-28 205 views
1

超级Golang noob here。来自其他包的golang结构

这是我的项目结构

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

我base_structs.go文件看起来像

package structs 

type Built_in_func func([] string) 

type Built_in struct { 
    s string 
    f Built_in_func 
} 

然后在我的main.go我已经导入了包,我喜欢引用的structs.Built_in_func结构。

这就是我想要做的事:

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}) 

但我发现了这个错误: unknown structs.Built_in field 's' in struct literal

再一次,我是一个超级golang小白。任何帮助:)

+0

请参阅[language spec](https://golang.org/ref/spec#Exported_identifiers)和[去旅行中的“基础知识”部分](https://tour.golang.org/basics/3) – JimB

回答

8

在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

+0

非常感谢!是超级有用的:) – glyif