回答

收藏

Go中的初始化结构数组

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

我是 Go 新手。这个问题让我疯了。你怎么在 Go 中初始化结构数组?8 a8 E; m  q" A) ~
[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。
* R9 n* c- W7 Z! n& _* B我应该把大括号放在哪里{来初始化我的结构数组?
5 F/ j1 Z. B1 ?2 V9 r" z                                                               
9 Y) [# ~2 U2 ^7 j9 C$ p( F& u    解决方案:                                                                8 [7 v! N/ U/ {' ^
                                                                看来你在这里试着直接用(几乎) C 代码。Go 有一些区别。
2 I' A2 L5 ]. n$ u, H首先,你不能初始化数组和切片const. 该术语const在 Go 有不同的含义,就像 C 中等。列表应定义为var。
4 \! m  e( e# f! J4 }1 e其次,作为一种风格规则,Go 更喜欢basenameOpts而不是basename_opts.
! W0 i1 F# G* J* H- ~/ n2 NcharGo 没有类型。你可能想要byte(或者rune假如你打算允许 unicode 代码点)。, q2 r0 e2 I7 I8 M4 X" K7 Y: p
在这种情况下,列表的声明必须具有赋值操作符。var x = foo。
/ M5 y( o% b% ]Go 分析器要求列表声明中的每个元素都以逗号结束。这包括最后一个元素。这是因为 Go 需要的地方会自动插入分号。工作需要更严格的语法。
例如:7 L5 Z" f, @8 l9 @5 X# J7 H
[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包中有多个函数,甚至可以在同一源文件中。
; `. L& Y/ l! t- j) j' c1 h[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 新手,我强烈建议你通读语言规范。它很短,写得很清楚。它将为你消除许多这些小特征。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则