在Go语言中,函数类型具有什么作用?

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

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
	})
)

huangapple
  • 本文由 发表于 2014年4月5日 23:01:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/22882542.html
匿名

发表评论

匿名网友

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

确定