I'm used to Java's String where we can pass null rather than "" for special meanings, such as use a default value.
In Go, string is a primitive type, so I cannot pass nil (null) to a parameter that requires a string.
I could write the function using pointer type, like this:
func f(s *string)
so caller can call that function either as
f(nil)
or
// not so elegant
temp := "hello";
f(&temp)
but the following is unfortunately not allowed:
// elegant but disallowed
f(&"hello");
What is the best way to have a parameter that receives either a string or nil?
You can declare an interface to restrict the type to string, and since interfaces also accept nil, you'd have both cases covered. This is how you can implement it:
type (
// An interface which accepts a string or a nil value.
//
// You can pass StrVal("text") or nil.
StrOrNil interface{ isStrOrNil() }
StrVal string // A string value for StrOrNil interface.
)
func (StrVal) isStrOrNil() {} // implement the interface
And this is how you use it:
func Foo(name StrOrNil) {
switch nameVal := name.(type) {
case StrVal:
fmt.Printf("String value! %s\n", string(nameVal))
default:
fmt.Println("Null value!")
}
}
func main() {
Foo(StrVal("hello world"))
Foo(nil)
}
Test it in the playground.
If you need to handle a possibble null value (becasue you are talking to a database that may provide them for example) the database/sql package has types such as sql.NullString and sql.NullInt64 that allow you to test if you have been provided with a value or not using their .Valid field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With