在结构体中初始化字符串指针。

huangapple go评论84阅读模式
英文:

initialize string pointer in struct

问题

Go新手问题:我正在尝试初始化以下结构体,并设置默认值。我知道如果"Uri"是一个字符串而不是指向字符串的指针(*string),它是可以工作的。但是我需要这个指针来比较两个结构体的实例,其中如果未设置Uri,则Uri将为nil,例如当我从JSON文件解组内容时。但是如何正确地初始化这样一个"静态默认"结构体呢?

type Config struct {
  Uri       *string
}

func init() {
  var config = Config{ Uri: "my:default" }
}

上面的代码会失败,显示错误信息:

cannot use "string" (type string) as type *string in field value
英文:

Go Newbie question: I am trying to init the following struct, with a default value. I know that it works if "Uri" is a string and not pointer to a string (*string). But i need this pointer for comparing two instances of the struct, where Uri would be nil if not set, e.g. when i demarshal content from a json file. But how can I initialize such a struct properly as a "static default"?

type Config struct {
  Uri       *string
}

func init() {
  var config = Config{ Uri: "my:default" }
}

The code above fails with

cannot use "string" (type string) as type *string in field value

答案1

得分: 89

无法获取常量值的地址(指向),这就是为什么你的初始化失败的原因。如果你定义一个变量并传递它的地址,你的示例将会工作。

type Config struct {
  Uri       *string
}

func init() {
  v := "my:default"
  var config = Config{ Uri: &v }
}
英文:

It's not possible to get the address (to point) of a constant value, which is why your initialization fails. If you define a variable and pass its address, your example will work.

type Config struct {
  Uri       *string
}

func init() {
  v := "my:default"
  var config = Config{ Uri: &v }
}

huangapple
  • 本文由 发表于 2017年3月4日 18:15:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/42594789.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定