2014-10-02 23 views
17

我是Go的新手。这个问题让我发疯。你如何在Go中初始化一系列结构?初始数组中的结构

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

编译器说它期待';'在[]选择后。

我应该在哪里放置大括号'{'来初始化我的struct数组?

谢谢

回答

30

它看起来像您尝试使用(几乎)直线上升的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进行阅读。它很短,写得很清楚。它会为你清除很多这些小小的特质。

18

添加这只是作为一个除了@ JIMT的出色答卷:

一个共同的方式来定义这一切在初始化时使用匿名结构:

var opts = []struct { 
    shortnm  byte 
    longnm, help string 
    needArg  bool 
}{ 
    {'a', "multiple", "Usage for a", false}, 
    { 
     shortnm: 'b', 
     longnm: "b-option", 
     needArg: false, 
     help: "Usage for b", 
    }, 
} 

这通常用于测试,以及定义少量测试用例并循环遍历它们。