How to have a function with a nullable string parameter in Go?
go, parameters, string
Solution
Warning: the following is pre-Go1 code. That is, it's from a pre-release version and is not valid Go code.
I thought some more about how I would implement this using a `struct`. Here's what I came up with:
type MyString struct {
val string;
}
func f(s MyString) {
if s == nil {
s = MyString{"some default"};
}
//do something with s.val
}
Then you can call `f` like this:
f(nil);
f(MyString{"not a default"});
Problem
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?