Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Golang:interface的一种使用技巧 #16

Open
wisecsj opened this issue Feb 16, 2019 · 2 comments
Open

Golang:interface的一种使用技巧 #16

wisecsj opened this issue Feb 16, 2019 · 2 comments

Comments

@wisecsj
Copy link
Owner

wisecsj commented Feb 16, 2019

假设我们定义了一个接口,譬如:fmt.Stringer

我们可以定义函数类型,让相同签名的函数自动实现某个接口

type FuncString func() string

func (f FuncString) String() string {
	return f()
}

func main() {
	var t fmt.Stringer = FuncString(func() string{
		return "hello,world"
	})

	fmt.Println(t)
}
@wisecsj
Copy link
Owner Author

wisecsj commented Feb 16, 2019

这个技巧在golang源码 net/http/server.go 也用到了

@wisecsj
Copy link
Owner Author

wisecsj commented Feb 16, 2019

type Handler interface {
	ServeHTTP(ResponseWriter, *Request)
}

// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
type HandlerFunc func(ResponseWriter, *Request)

// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
	f(w, r)
}

这样的话,任何一个具有func(ResponseWriter, *Request)签名的函数通过类型转换为HandlerFunc即可自动实现Handler接口

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant