The interfaces portion of Golang CodeReviewComments
states:
Go interfaces generally belong in the package that uses values of the interface type, not the package that implements those values. The implementing package should return concrete (usually pointer or struct) types: that way, new methods can be added to implementations without requiring extensive refactoring.
Yet, Go's context.go
module both defines the Context
interface and implements it for type emptyCtx int
and type cancelCtx struct
.
Note, the portion listed above says they "generally" belong in the package that uses values of the interface type — so I understand that this is not a strict rule.
However, I am curious as to what the criteria is that makes it OK for them to do this in the context
package.
Also, this assumes CodeReviewComments
is a canonical resource for Go code reviews and style guide.
CodePudding user response:
Defining implementations of an interface in the same package is actually pretty common, especially when implementing a strategy pattern or chain of responsibility(like context).
Take the net package for example, it defines the Listener
interface, but also TCPListener
, UDPListener
, and UnixListener
. In this case it would be illogical to place the functionality in another package.
The io package does a similar thing with the readers and writers.
Another handy pattern is to define a function alias for interfaces which only have 1 function. Like how HandlerFunc implements Handler, allowing users to cast closures as HandlerFunc so they don't have to define their own type, which is much more work.