在Go语言中的参数传递

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

Parameter passing in Go

问题

假设我有一个类型为http.HandleFunc的方法。

  1. type HandlerFunc func(ResponseWriter, *Request)

我想将它包装在另一个相同类型的方法周围,类似于这样:

  1. func MyWrapper(res http.ResponseWriter, req *http.Request) {
  2. // 做一些事情
  3. AnotherMethod(res, req) // <- 问题指的是这一行
  4. // 做更多的事情
  5. }
  6. func AnotherMethod(res http.ResponseWriter, req *http.Request) {
  7. // 主要逻辑
  8. }

如果我理解正确的话,当我调用AnotherMethod(res, req)时,我正在传递一个(值的)res的__副本__给AnotherMethod,这意味着这个对象现在在内存中被复制了。

有没有办法我可以传递一个指向res的__指针__给AnotherMethod,然后在那里解引用,以避免复制res的值?或者我理解错了什么?

(在AnotherMethod内部使用指向(值的)res的指针是行不通的,因为http.ResponseWriter中所有方法的接收者都是值,而不是指针)

英文:

Suppose I have a method of type http.HandleFunc

  1. type HandlerFunc func(ResponseWriter, *Request)

And I want to wrap it around another method of the same type, somewhat like this:

  1. func MyWrapper(res http.ResponseWriter, req *http.Request) {
  2. // do stuff
  3. AnotherMethod(res, req) // <- question refers to this line
  4. // do more stuff
  5. }
  6. func AnotherMethod(res http.ResponseWriter, req *http.Request) {
  7. // main logic
  8. }

If I'm getting this right; when I call AnotherMethod(res, req) I'm passing a copy of (the value of) res to AnotherMethod, meaning that this object is now duplicated in memory.

Is there a way I could pass a pointer to res to AnotherMethod and then dereference there, in order to not copy the value of res? or am I not understanding something?

(Working with a pointer to (the value of) res inside AnotherMethod won't work because the receivers of all methods in http.ResponseWriter are values and not pointers)

答案1

得分: 5

http.ResponseWriter 是一个接口类型。这意味着它可以是引用类型或值类型,取决于底层类型是什么以及它如何实现接口。

在这种情况下,res 是未导出类型 *http.response 的一个实例。正如你所见,它是一个指针类型,这意味着你可以传递它而不创建整个结构的副本。

要查看接收到的接口值内部保存的真实类型,你可以这样做:fmt.Printf("%T\n", res)。它应该打印出:*http.response

关于 Go 中接口类型的工作原理的更多信息,我建议阅读有关该主题的Go 规范

英文:

http.ResponseWriter is an interface type. Which means it can be both a reference or value type, depending on what the underlying type is and how it implements the interface.

In this case, res is an instance of the unexported type *http.response. As you can see, it is a pointer type, which means you can pass it around without creating a copy of the whole structure.

To see what real type is held inside an interface value you are receiving, you can do this: fmt.Printf("%T\n", res). It should print: *http.resonse.

For more information on how interface types work in Go, I recommend reading the Go specification on the subject.

huangapple
  • 本文由 发表于 2012年1月10日 23:41:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/8805978.html
匿名

发表评论

匿名网友

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

确定