英文:
What purpose function types have in Go?
问题
package main
import (
"fmt"
)
type A func(int, int)
func (this A) Serve() {
fmt.Println("function 1")
}
func Serve(int, int) {
fmt.Println("function 2")
}
func main() {
a := A(Serve)
a.Serve() // function 1
}
Serve函数可以转换为类型A,它也是一个函数,但是,我不明白我们何时以及为什么要使用这种方法,将一个函数类型转换为另一个函数类型?我的示例似乎没有意义。
int、struct等是类型,从底层数据结构的角度来看,函数类型与常见的类型(如int和struct)有何不同?
非常感谢!
英文:
package main
import(
"fmt"
)
type A func (int,int)
func (this A) Serve() {
fmt.Println("function 1")
}
func Serve(int,int) {
fmt.Println("function 2")
}
func main() {
a := A(Serve)
a.Serve() // function 1
}
Function Serve can be converted to type A,which is also a function,but,I just don't get the idea of when and why we should use this approach,to deal with what kind of problem should we convert a function type to another?My example seems to be meaningless.
int,struct etc. are types,and what exactly is the function type different from the common known types like int and struct,from the underlying data structure perspective of view?
Thanks a lot!
答案1
得分: 4
确实有点令人困惑。我见过这种技术被用来使普通函数符合接口的要求,而不需要创建结构体并将函数作为该结构体的方法,或者使用其他类似的技术。
一个很好的例子可以在标准的http库中找到。你可以看到以下类型定义:
type HandlerFunc func(ResponseWriter, *Request)
它有一个方法:
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}
这使得它可以作为http.Handler
接口来使用,该接口定义如下:
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
这样你就可以在普通函数上调用http.ListenAndServe
,而不使用默认的http mux。将函数包装为http.Handler
允许你创建一个"无mux"的服务器。
因此,你可以这样做:
http.ListenAndServe(":8080",
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 做些什么
})
)
英文:
It's a bit confusing indeed. I've seen this technique used to make an ordinary function compliant with an interface without the hassle of creating a struct and making the function a method of this struct - or other similar techniques.
A great example can be found in the standard http library. you have the type
type HandlerFunc func(ResponseWriter, *Request)
And it has the method:
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}
This allows it to be used as the http.Handler
interface which looks like this:
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
This allows you to call http.ListenAndServe
on an ordinary function without using the default http mux. wrapping the function as an http.Handler
allows you to create a "mux-less" server.
Thus you can do something like:
http.ListenAndServe(":8080",
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//la di da
})
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论