Home > Software design >  Print the Content of *string
Print the Content of *string

Time:09-10

There are so many verbs for the fmt.Printf family, but going through the documentation (https://pkg.go.dev/fmt) I can't find an easy way to print the content of a *string and alike (with something like <nil> in case it's a nil pointer). I was hoping that %v might serve that purpose, but that returns the pointer's address instead. Am I missing something here or do I have to resort to utility methods everytime I want to write the content of such a pointer value into an error message or a log entry?

CodePudding user response:

While not as convenient as a verb, here's one utility function will work for any pointer type:

package main

import "log"

func safeDeref[T any](p *T) T {
    if p == nil {
        var v T
        return v
    }
    return *p
}

func main() {
    s := "hello"
    sp := &s
    var np *string

    log.Printf("s: %s, sp: %s, np: %s", s, safeDeref(sp), safeDeref(np))
}
2022/09/06 15:01:50 s: hello, sp: hello, np: 

*string is pretty rare in idiomatic Go. Unless you really need nil, I'd suggest just using string.

  •  Tags:  
  • go
  • Related