英文:
Parameter passing in Go
问题
假设我有一个类型为http.HandleFunc
的方法。
type HandlerFunc func(ResponseWriter, *Request)
我想将它包装在另一个相同类型的方法周围,类似于这样:
func MyWrapper(res http.ResponseWriter, req *http.Request) {
// 做一些事情
AnotherMethod(res, req) // <- 问题指的是这一行
// 做更多的事情
}
func AnotherMethod(res http.ResponseWriter, req *http.Request) {
// 主要逻辑
}
如果我理解正确的话,当我调用AnotherMethod(res, req)
时,我正在传递一个(值的)res
的__副本__给AnotherMethod
,这意味着这个对象现在在内存中被复制了。
有没有办法我可以传递一个指向res
的__指针__给AnotherMethod
,然后在那里解引用,以避免复制res
的值?或者我理解错了什么?
(在AnotherMethod
内部使用指向(值的)res
的指针是行不通的,因为http.ResponseWriter
中所有方法的接收者都是值,而不是指针)
英文:
Suppose I have a method of type http.HandleFunc
type HandlerFunc func(ResponseWriter, *Request)
And I want to wrap it around another method of the same type, somewhat like this:
func MyWrapper(res http.ResponseWriter, req *http.Request) {
// do stuff
AnotherMethod(res, req) // <- question refers to this line
// do more stuff
}
func AnotherMethod(res http.ResponseWriter, req *http.Request) {
// main logic
}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论