55

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
Mandragor
  • 4,684
  • 7
  • 25
  • 40
  • 1
    You can use package [pointer](https://github.com/xorcare/pointer), for example: var _ *string = pointer.String("my:default") – Xor Nov 07 '19 at 10:26

1 Answers1

89

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 }
}
Nadh
  • 6,987
  • 2
  • 21
  • 21
  • 40
    Is there a way to do this in a one liner so that the `v := "my:default"` wouldn't be needed? – Zamicol Nov 29 '19 at 08:51
  • 2
    The accepted answer here also applies to strings. There are several ways to do it as a one-liner, but they are ugly: https://stackoverflow.com/questions/30716354/how-do-i-do-a-literal-int64-in-go/30716481 – Ian Gustafson Jan 06 '20 at 15:47
  • I was also looking for a one-liner, but unfortunately, this looks better and easy to read. – yashjain12yj Sep 21 '20 at 11:17
  • 8
    @Zamicol in my previous and current company, we simply create helper functions (StrPtr(val string), Int64Ptr(val int64), etc). I think it's a common enough situation to make it useful. – Arthur Feldman May 05 '21 at 09:45
  • 4
    A better way without new variable assignment: `func String(v string) *string { return &v }` func init(){ var config = Config{ Uri: String("my:default") } } – Yulin Nov 05 '21 at 19:21