Elliot Chance
Elliot Chance

Reputation: 5736

Combining or extending interfaces?

I have two interfaces:

type Request interface {
    Version() string
    Method() string
    Params() interface{}
    Id() interface{}
}

type Responder interface {
    NewSuccessResponse() Response
    NewErrorResponse() Response
}

I would like to make a RequestResponder interface which combines both of these. Is this possible, or do I have to create a third interface with all 6 functions?

Upvotes: 7

Views: 5048

Answers (1)

user142162
user142162

Reputation:

Interface embedding is allowed, as documented in the spec:

An interface T may use a (possibly qualified) interface type name E in place of a method specification. This is called embedding interface E in T; it adds all (exported and non-exported) methods of E to the interface T.

This is done throughout Go's standard library (one example is io.ReadCloser).

In your question, RequestResponder would be constructed as:

type RequestResponder interface {
    Request
    Responder
}

Upvotes: 10

Related Questions