How to Return Nil String in Go?

后端 未结 3 1251
小蘑菇
小蘑菇 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:30

    Go has built-in support for multiple return values:

    This feature is used often in idiomatic Go, for example to return both result and error values from a function.

    In your case it could be like this:

    func test() (response string, err error) {
        if runtime.GOOS != "linux" {  
            return "", nil
        } else {
            /* blablabla*/
        }
    }
    

    And then:

    response, err := test()
    if err != nil { 
        // Error handling code
        return;
    }
    
    // Normal code 
    

    If you want to ignore the error, simply use _:

    response, _ := test()
    // Normal code
    

提交回复
热议问题