Function within a structure. What for?

What is the use-case / advantage of defining a function inside a struct in go?

type demo struct {
    F func()
}

      

+3


source to share


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


It allows you to customize a function for a type without doing it from that type.



-1


source







All Articles