Golang传递nil作为函数的可选参数? [英] Golang pass nil as optional argument to a function?
问题描述
在Golang中, http.NewRequest
具有如下规范:
In Golang, http.NewRequest
has a specification like this:
func NewRequest(method, urlStr string, body io.Reader) (*Request, error)
但是,如果我不想将 body
传递给 io,则可以将
对象,如下所示: nil
作为 body
选项传递.Reader
However, I can pass nil
as the body
option if I don't want to pass the body
to an io.Reader
object, like this:
req, err := http.NewRequest("GET", "http://www.blahblah.org", nil)
如何在代码中实现此功能?我有一个函数,我希望传递一个可选的字符串值,以便它可以分页显示API结果,但是如果我将 nil
传递给字符串输入,则会得到以下信息:
How do I implement this functionality in my code? I have a function that I want to pass an optional string value so that it can page through API results however if I pass a nil
to the string input I get this:
./snippets.go:32:无法将nil转换为字符串类型
./snippets.go:32: cannot convert nil to type string
我的函数的参数如下:
func getChallenges(after string) ([]challenge, string, error)
推荐答案
Go没有可选"参数作为其他语言中普遍理解的概念; nil
只是接口的零值(在本例中为 io.Reader
).
Go does not have "optional" arguments as a generally understood concept in other languages; nil
is just the zero value for an interface (io.Reader
in this case).
字符串的等效零值是一个空字符串:
The equivalent zero value for a string is an empty string:
getChallenges("")
如果要接受0个或多个相同的参数类型,请使用可变参数语法:
If you want to accept 0 or more of the same argument type, you use the variadic syntax:
func getChallenges(after ...string) ([]challenge, string, error)
这篇关于Golang传递nil作为函数的可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!