如何使用不可为空的索引和 0 索引列表

如果我在结构中传递一个 int 值(在我的特定情况下,rpc 参数),则该语言不允许该属性为零。int 的空值为 0。


但 Go 使用 0 索引数组。我需要一种方法来区分空值和索引 0。对于这个问题,有没有一个惯用的go解决方案?


// this is psuedo-code I had written before hitting this problem

if (args.maybeIndex != nil) {

  doSomething(sliceOfNodes[args.maybeIndex])

}



蝴蝶不菲
浏览 70回答 1
1回答

人到中年有点甜

如果按值对 int 进行编码,则对此无能为力 - 默认值为 0。确保在 Go 中编码的可空性的常见方法是使用指针类型。使用 代替 a 可以区分“无”和 0。*intint例如,使用 JSON 示例,请考虑以下结构:type Options struct {  Id      *string `json:"id,omitempty"`  Verbose *bool   `json:"verbose,omitempty"`  Level   *int    `json:"level,omitempty"`  Power   *int    `json:"power,omitempty"`}这些数据:{  "id": "foobar",  "verbose": false,  "level": 10}请注意,未指定“电源”。你可以写一个反序列化器:func parseOptions(jsn []byte) Options {  var opts Options  if err := json.Unmarshal(jsonText, &opts); err != nil {    log.Fatal(err)  }  if opts.Power == nil {    var v int = 10    opts.Power = &v  }  return opts}这会将默认值设置为“power”(如果未指定)。这使您可以区分“不存在”和“存在并且其值为0”。powerpower如果您的编码/ RPC机制不允许指针,则可以通过具有另一个名为“存在索引”或类似内容的布尔字段来解决此问题。最后,考虑设计程序,使其能够适应“未设置”和“设置为默认值”之间的差异。IOW,只需接受默认值和未指定的数据是相同的。从长远来看,这将导致更干净的设计和代码,并且不易出错。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go