Golang传递nil作为函数的可选参数?

13 go

在golang中,http.NewRequest有这样的规范:

func NewRequest(method, urlStr string, body io.Reader) (*Request, error)
Run Code Online (Sandbox Code Playgroud)

但是,如果我不想将主体传递给io.Reader对象,我可以传递nil作为body选项,如下所示:

req, err := http.NewRequest("GET", "http://www.blahblah.org", nil)
Run Code Online (Sandbox Code Playgroud)

如何在我的代码中实现此功能?我有一个函数,我想传递一个可选的字符串值,以便它可以通过API结果页面,但是如果我传递一个nil到字符串输入我得到这个:

func getChallenges(after string) ([]challenge, string, error)
Run Code Online (Sandbox Code Playgroud)

我的函数的参数如下所示:

func NewRequest(method, urlStr string, body io.Reader) (*Request, error)
Run Code Online (Sandbox Code Playgroud)

Jim*_*imB 11

Go中没有参数是"可选的"; nil只是接口的零值(io.Reader在这种情况下).

字符串的等效零值是空字符串:

getChallenges("")
Run Code Online (Sandbox Code Playgroud)

如果要接受0或更多相同的参数类型,可以使用可变参数语法:

func getChallenges(after ...string) ([]challenge, string, error)
Run Code Online (Sandbox Code Playgroud)


coq*_*uin 9

您可以修改函数以接收指针值,如下所示:

func getChallenges(after *string) ([]challenge, string, error)

然后你可以nil作为参数传递给它.但是不要忘了检查afternil取消引用它之前你的函数的内在价值,或者你会得到一个零指针异常:

func getChallenges(after *string) ([]challenge, string, error) {
    if after == nil {
        // No value specified
    } else {
        fmt.Printf("After: %s\n", *after) // Note pointer dereferencing with "*"
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

另外一个选项:

只需使用两个功能:

func getChallenges(after string) {}

func getAllChallenges() {
    return getChallenges(/* some default value here */)
}
Run Code Online (Sandbox Code Playgroud)

  • 将参数设置为* string的一个巨大缺点是,您不能使用字符串文字的地址,也不能自动为您装箱该字符串。https://play.golang.org/p/d4jvq5xrAk (3认同)