2

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?

Elliot Chance
  • 5,526
  • 10
  • 49
  • 80
  • It may be worth noting that APIs that take in a one-method `interface` could be re-written as taking a function type. See https://stackoverflow.com/a/63557675/12817546. –  Aug 25 '20 at 01:11

1 Answers1

5

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
}