它看起来像您尝试使用(几乎)直线上升的C代码在这里。 Go有一些差异。
- 首先,您不能初始化数组和切片作为
const
。术语const
在Go中的含义与C中的不同。该列表应该定义为var
。
- 其次,作为一种风格规则,Go更喜欢
basenameOpts
而不是basename_opts
。
- Go中没有
char
类型。你可能想要byte
(或rune
,如果你打算允许unicode码点)。
- 在这种情况下,列表的声明必须具有赋值运算符。例如:
var x = foo
。
- Go的解析器要求列表声明中的每个元素以逗号结尾。 这包括最后一个元素。这是因为Go会在需要时自动插入 分号。这需要更严格的语法才能工作。
例如:
type opt struct {
shortnm byte
longnm, help string
needArg bool
}
var basenameOpts = []opt {
opt {
shortnm: 'a',
longnm: "multiple",
needArg: false,
help: "Usage for a",
},
opt {
shortnm: 'b',
longnm: "b-option",
needArg: false,
help: "Usage for b",
},
}
一种替代方法是用它的类型来声明列表,然后使用init
函数来填充它。如果您打算使用数据结构中的函数返回的值,这非常有用。 init
函数在程序初始化时运行,并且在执行main
之前保证完成。您可以在一个包中包含多个init
函数,甚至可以在同一个源文件中包含多个函数。
type opt struct {
shortnm byte
longnm, help string
needArg bool
}
var basenameOpts []opt
func init() {
basenameOpts = []opt{
opt {
shortnm: 'a',
longnm: "multiple",
needArg: false,
help: "Usage for a",
},
opt {
shortnm: 'b',
longnm: "b-option",
needArg: false,
help: "Usage for b",
},
)
}
既然您是Go的新手,我强烈建议您通过the language specification进行阅读。它很短,写得很清楚。它会为你清除很多这些小小的特质。