Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a function with a nullable string parameter in Go?

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?

like image 361
Randy Sugianto 'Yuku' Avatar asked Nov 25 '09 19:11

Randy Sugianto 'Yuku'


2 Answers

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.

like image 79
rodrigocfd Avatar answered Sep 20 '22 19:09

rodrigocfd


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.

like image 21
James Matheson Avatar answered Sep 19 '22 19:09

James Matheson