回答

收藏

Go中的初始化结构数组

技术问答 技术问答 337 人阅读 | 0 人回复 | 2023-09-12

我是 Go 新手。这个问题让我疯了。你怎么在 Go 中初始化结构数组?& b! k2 f* d- _! o( s
[code]type opt struct    shortnm      char    longnm,help string    needArg      bool}const basename_opts []opt         opt            shortnm: 'a  longnm: "multiple",            needArg: false,            help: "Usage for a"}         opt            shortnm: 'b  longnm: "b-option",            needArg: false,            help: "Usage for b"}   code]编译器说它有预期;后[]opt。
4 F; ]+ ?; ^  ^% }我应该把大括号放在哪里{来初始化我的结构数组?
+ s# {( N" {( L! o8 e                                                                % n  E4 f1 J6 V% a! M  z3 i
    解决方案:                                                                + M) E  A! G6 \! U& a" E
                                                                看来你在这里试着直接用(几乎) C 代码。Go 有一些区别。
& b* g/ z! ^1 }, j4 h/ K0 `  Z& p9 R首先,你不能初始化数组和切片const. 该术语const在 Go 有不同的含义,就像 C 中等。列表应定义为var。2 t' N( X3 m/ j. ]
其次,作为一种风格规则,Go 更喜欢basenameOpts而不是basename_opts.
2 |- R8 J! T1 p6 L' Z2 W0 XcharGo 没有类型。你可能想要byte(或者rune假如你打算允许 unicode 代码点)。
4 ^& d5 T, _; H在这种情况下,列表的声明必须具有赋值操作符。var x = foo。
( S, u$ K8 @. s9 U9 L4 eGo 分析器要求列表声明中的每个元素都以逗号结束。这包括最后一个元素。这是因为 Go 需要的地方会自动插入分号。工作需要更严格的语法。
例如:9 V! e0 M0 `! v' G, q7 p, Z* v
[code]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",}code]另一种方法是用它的类型声明列表,然后使用一个init填充函数。如果您计划在数据结构中使用函数返回值,则非常有用。init函数在程序初始化时运行,并保证main执行前完成。你可以。init包中有多个函数,甚至可以在同一源文件中。! m, m7 D, O# G6 c" J' d
[code]    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",          code]由于您是 Go 新手,我强烈建议你通读语言规范。它很短,写得很清楚。它将为你消除许多这些小特征。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则