How to Return Nil String in Go?

后端 未结 3 1240
小蘑菇
小蘑菇 2021-02-06 23:51

I have a function which returns a string under certain circumstances, namely when the program runs in Linux or MacOS, otherwise the return value should be nil in order to omit s

3条回答
  •  梦谈多话
    2021-02-07 00:43

    If you can't use "", return a pointer of type *string; or–since this is Go–you may declare multiple return values, such as: (response string, ok bool).

    Using *string: return nil pointer when you don't have a "useful" string to return. When you do, assign it to a local variable, and return its address.

    func test() (response *string) {
        if runtime.GOOS != "linux" {
            return nil
        } else {
            ret := "useful"
            return &ret
        }
    }
    

    Using multiple return values: when you have a useful string to return, return it with ok = true, e.g.:

    return "useful", true
    

    Otherwise:

    return "", false
    

    This is how it would look like:

    func test() (response string, ok bool) {
        if runtime.GOOS != "linux" {
            return "", false
        } else {
            return "useful", true
        }
    }
    

    At the caller, first check the ok return value. If that's true, you may use the string value. Otherwise, consider it useless.

    Also see related questions:

    How do I represent an Optional String in Go?

    Alternatives for obtaining and returning a pointer to string: How do I do a literal *int64 in Go?

提交回复
热议问题