Featured image

Returning to my previous post, in which I claimed there was no standard way to get the address of a string literal, I was using an old version of Golang, specifically 1.21. In the latest version, 1.26, it turns out you can pass a string literal to the built-in new function, and it will return its address. I learned this by reviewing the gox library source code.

package main

import "fmt"

type Person struct {
  name string
  lang *string
}

func (p *Person) Lang(d string) string {
  lang := d
  if p.lang != nil {
    lang = *p.lang
  }
  return lang
}

func main() {
  p := &Person{name: "Artem", lang: new("Go")}
  fmt.Printf("name: %s, lang: %s\n", p.name, p.Lang("no lang"))
}