What is the use case/advantage of defining a function within a structure in go?
type demo struct {
F func()
}
What is the use case/advantage of defining a function within a structure in go?
type demo struct {
F func()
}
I think that the best answer would be an example.
Look at Client.CheckRedirect
in the documentation.
type Client struct {
// (...)
CheckRedirect func(req *Request, via []*Request) error
}
This is a function that is being invoked whenever a http.Client
has a redirect response. By the fact, that this function is a public property, you can set this when creating the Client
object or afterwards and thus you can define custom behaviour on such case.
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
}
Function properties are just a delegates of custom behaviour (and not only!).
Another example would be creating an object which has an event.
type Example struct {
EventHandler func(params []interface{})
}
You can specify a behaviour on that event by setting the Example.EventHandler
property.