How to have a function with a nullable string parameter in Go?
Posted
by yuku
on Stack Overflow
See other posts from Stack Overflow
or by yuku
Published on 2009-11-25T19:24:24Z
Indexed on
2010/03/19
16:21 UTC
Read the original article
Hit count: 371
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?
© Stack Overflow or respective owner