在 Go 中初始化结构数组

新手上路,请多包涵

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

编译器说它期待 ;[]opt 之后。

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

原文由 daniel.widyanto 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 531
1 个回答

看起来您正在尝试(几乎)直接使用 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 的新手,我强烈建议您阅读 语言规范。它很短,写得很清楚。它会为你清除很多这些小怪癖。

原文由 jimt 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题