Featured image

Whenever I return to programming in Golang, I always encounter the lack of a standard solution for obtaining the address of a string literal. This is especially necessary when initializing a pointer to a string in a structure, for example, when it contains an optional string field. But I’m not alone in this problem, as this issue, which proposed adding a method for obtaining the address of a literal to the standard library, was discussed back in 2020.

I understand the maintainers’ position, which is to avoid using pointers for optional values in structs (and if you want to use them, implement these methods yourself). To some extent, I agree with them and support their choice. But what bothers me most isn’t the fact that they haven’t added address-receiving methods to the standard library, but rather that the maintainers’ recommended approach isn’t included in the standard library, forcing you to use third-party solutions like nan, mo, or optional.

Which solution will you choose when implementing a struct with an optional field?

package main

import "fmt"

type Person struct {
  name string
  lang *string
}

func StrPtr(s string) *string { return &s }

func StrWithDefault(p *string, d string) string {
  v := d
  if p != nil {
    v = *p
  }
  return v
}

func main() {
  l := "Go"
  p := &Person{name: "Artem", lang: &l} // &Person{name: "Artem"}
  lang := "no lang"
  if p.lang != nil {
    lang = *p.lang
  }
  fmt.Printf("name: %s, lang: %s\n", p.name, lang)

  p2 := &Person{name: "Artem", lang: StrPtr("Go")} // &Person{name: "Artem"}
  fmt.Printf("name: %s, lang: %s\n", p2.name, StrWithDefault(p2.lang, "no lang"))
}