Skip to content
This repository has been archived by the owner on Jun 27, 2023. It is now read-only.

Suggestion: add a var declaration to document the matched interface #1

Closed
rickb777 opened this issue Jun 20, 2015 · 2 comments
Closed

Comments

@rickb777
Copy link

I have a suggestion that the generated mock implementation code could include a var that illustrates the implemented interface.

This has become moderately widespread idiomatic practice, mostly for the purpose of documenting a type that matches an interface. Because Go doesn't include explicit syntax matching types to interfaces (and it doesn't need to, which is a good thing), this idiomatic practice has emerged instead.

An example is most useful here. Suppose I want to mock net/http/ResponseWriter. Using mockgen, I get

// Mock of ResponseWriter interface
type MockResponseWriter struct {
    ctrl     *gomock.Controller
    recorder *_MockResponseWriterRecorder
}

My suggestion is that mockgen should also generate this:

var _ *http.ResponseWriter = &MockResponseWriter{}

it would be clear to anyone reading the code that there is an implied 'implements' relationship between the type MockResponseWriter and the interface ResponseWriter. We know this because the compiler type-checks the var declaration in a way that guarantees it to be true (given that the compiler is successful). The var introduces an unnamed variable that is never used; presumably the compiler can notice that it's unused and eliminate it from the binary code.

@rickb777
Copy link
Author

Here is another example of use of this practice:
golang/net/icmp/endpoint.go line 17

var _ net.PacketConn = &PacketConn{}

@dsymonds
Copy link
Contributor

It's a nice idea, but unfortunately doesn't work in the general situation because it then requires the mock package to depend on the package holding the interface being mocked. Usually that wouldn't be a big deal, but there are situations where that package can be quite bulky, and adding a dependency edge just for this would be the wrong tradeoff.

# for free to subscribe to this conversation on GitHub. Already have an account? #.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants