Making @sepehr's comment in the previous answer an answer of it's own, and adding some conversion functions I find helpful.
From Russ Cox
There's no effective difference. We thought people might want to use NullString because it is so common and perhaps expresses the intent more clearly than *string. But either will work
In fact, a few generic functions make it easy to convert from *string
and sql.NullString
with a minimum of fuss:
func DerefOrEmpty[T any](val *T) T {
if val == nil {
var empty T
return empty
}
return *val
}
func IsNotNil[T any](val *T) bool {
return val != nil
}
Usage:
func main() {
var comment string = "hello"
commentPtr := &comment
sqlStrComment := sql.NullString{
String: DerefOrEmpty(commentPtr),
Valid: IsNotNil(commentPtr),
}
fmt.Printf("%#v\n", sqlStrComment)
commentPtr = nil
sqlStrComment = sql.NullString{
String: DerefOrEmpty(commentPtr),
Valid: IsNotNil(commentPtr),
}
fmt.Printf("%#v\n", sqlStrComment)
}
Playground link at https://go.dev/play/p/KFNHe2iJmGU