2014-10-02 22 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", 
    }, 
} 

這通常用於測試,以及定義少量測試用例並循環遍歷它們。