确定从go函数返回什么

huangapple go评论80阅读模式
英文:

Determining what is returned from a go function

问题

给定这个函数:

func (c *Firehose) PutRecord(input *PutRecordInput) (*PutRecordOutput, error) {
    req, out := c.PutRecordRequest(input)
    return out, req.Send()
}

我发现这个调用是有效的:

err, _ := svc.PutRecord(putRecordInput)

然而,我对函数签名中的这部分仍然不太清楚:

(*PutRecordOutput, error)

我的问题是,我是否总是可以通过返回行中指定的内容来确定函数返回的内容,就像在这个例子中是这样的:

return out, req.Send()

英文:

Given this function:

func (c *Firehose) PutRecord(input *PutRecordInput) (*PutRecordOutput, error) {
	req, out := c.PutRecordRequest(input)
	return out, req.Send()
}

I found that this invocation works:

err, _ := svc.PutRecord(putRecordInput)

However I'm still not very clear on what this means in function signature:

(*PutRecordOutput, error)

My question is, can I always determine what is returned from a function by what is specified in the return line, which in this case is:

return out, req.Send()

答案1

得分: 2

这部分函数签名的含义是函数返回的内容。

(*PutRecordOutput, error)

因此,这个函数将返回一个指向PutRecordOutput的指针,以及一个error(按照惯例,如果没有错误发生,会返回nil)。

如果你查看函数的源代码,return语句必须与此一致,这也可以帮助你理解返回值是如何构建的。

但是,请注意,在某些情况下,你可能会看到命名的输出参数,例如:

(output *PutRecordOutput, err error)

在这种情况下,outputerr将是函数内部的有效局部变量,你可能会看到一个简单的返回语句,如下所示:

return

只需记住,这样的返回语句隐含地相当于:

return output, err

英文:

This part of the function signature is exactly what the function returns.

(*PutRecordOutput, error)

So this one will return a pointer to a PutRecordOutput plus an error (which by convention is returned as nil if no error occurred).

If you look at the source code for the function, return statements will have to be consistent with that, so that can also help you understand how the return values are built.

But, please note that in some cases you could have named output arguments, like:

(output *PutRecordOutput, err error)

In that case, output and err will be valid local variables inside the function, and you might see a plain return statement like this:

return

Just keep in mind that one would implicitly be like doing:

return output, err

huangapple
  • 本文由 发表于 2017年6月30日 21:49:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/44848112.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定