Function within a structure. What for?
2 answers
I think the best answer would be an example.
Have a look Client.CheckRedirect
in the documentation.
type Client struct {
// (...)
CheckRedirect func(req *Request, via []*Request) error
}
This is the function that gets called whenever it http.Client
has a redirect response. Since this function is public, you can set it when creating an object Client
or afterwards, and thus you can define custom behavior in such a case.
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
}
Functional properties are just delegates for custom behavior (and more!).
Another example would be creating an object with an event.
type Example struct {
EventHandler func(params []interface{})
}
You can specify the behavior of this event by setting the property Example.EventHandler
.
+6
source to share