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

This question already has an answer here:

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
</div>

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