The problem

If you have ever worked with the Amazon Web Services SDK for Go or Kubernetes Custom Resource Definitions (CRD) in Go, then you are no doubt quite familiar when some argument or field takes a pointer to a string or int, for example (Go playground):

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type request struct {
  6. host *string
  7. port *int
  8. }
  9. func print(r request) {
  10. fmt.Print("request: host=")
  11. if r.host != nil {
  12. fmt.Print(*r.host)
  13. }
  14. fmt.Print(", port=")
  15. if r.port != nil {
  16. fmt.Printf("%d", *r.port)
  17. }
  18. fmt.Println()
  19. }
  20. func main() {
  21. print(request{
  22. host: nil, // needs a *string
  23. port: nil, // needs a *int
  24. })
  25. }

There are two, common — albeit far from perfect — solutions for addressing the issue:


Next: Local variables