如何在Go语言中正确使用这些变量来调用一个单独的函数?

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

How do I properly use these variables in a separate function in Go?

问题

抱歉,这可能是一个非常基础的问题。

我正在使用httplistenAndServe函数,并且它调用了以下函数:

func library(writer http.ResponseWriter, request *http.Request)

该函数中的许多代码在其他地方也会使用,所以我想将它提取到另一个函数中,例如:

func commonFunction(doThing bool, writer http.ResponseWriter, request *http.Request)

但是,如果我从library函数将这两个变量传递给它,那么commonFunction函数的函数头是否正确?

我应该这样调用它:commonFunction(true, writer, request)吗?

我主要是困惑于是否应该传递这些变量的指针?对于http.Request来说,不传递指针似乎是有道理的,因为它已经是一个指针,但是http.ResponseWriter呢?我肯定不想重新创建该变量,对吗?

英文:

Apologies for what is likely a very elementary question.

I'm using http's listenAndServe, and it calls the following function:

func library(writer http.ResponseWriter, request *http.Request)

A lot of the code contained in that function applies elsewhere, so I wanted to bring it out into another function, such as:

func commonFunction(doThing bool, writer http.ResponseWriter, request *http.Request)

But is that function header for commonFunction correct if I'm passing those two variables from library into it?

Would I call it as commonFunction(true, writer, request)?

I'm mostly confused if I should be passing pointers to these variables? It would make sense not to for http.Request as it's already a pointer, but what about http.ResponseWriter, surely I don't want to recreate the variable?

答案1

得分: 3

你的签名看起来不错。当人们刚开始在Go中进行Web开发时,很多人会忽视一个重要的部分,那就是writer http.ResponseWriter是一个接口值。在Go中,接口值是引用类型,这意味着你传递的writer变量已经内部包含了指向满足该接口的具体值的指针。你可以放心地将你的writer传递给commonFunction,它已经是一个引用了。

英文:

Your signature looks fine. One part many people overlook when they first start doing web work in Go is that the writer http.ResponseWriter is an interface value. In Go interface values are reference types meaning that the writer variable you're being passed already internally contains a pointer to the concrete value that's satisfying that interface. You can feel free to pass your writer on to commonFunction and it's already a reference.

huangapple
  • 本文由 发表于 2016年11月4日 11:04:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/40414643.html
匿名

发表评论

匿名网友

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

确定