proposal: Derive interface type from a concrete type #23886
Labels
FrozenDueToAge
LanguageChange
Suggested changes to the Go language
Proposal
v2
An incompatible library change
Milestone
I'm not sure if this is a good idea. But I have thought about it several times and would like to share it in case it has not been considered. This is for future versions of Go (probably Go 2.0).
Proposal
It would be nice if there is a way to define an interface type that is the method set of some arbitrary type
T
. My proposal is to simply generalize the existing interface embedding:Currently
T
can only be an interface. The proposal is to allow other types as well, and the interface contains the method sets of all embedded types.T
must not be a pointer type, and for non-interface type,*T
can also be embeded.Application
Suppose I need to write the following function that uses a concrete type
someservice.Client
:To write unit test for
MyFunc
, I want to fakesomeservice.Client
. An easy way is to change the above code toHere
myInterface
contains a subset of the method set of*someservice.Client
. However, if the method set is large, and if I need to change code back and forth (so it's hard to determine which methods are used), it would be tedious to keepmyInterface
up to date. The proposal will solve the problem:Note 1
A google search shows that people have written tools to generate interface from struct: https://github.com/vburenin/ifacemaker (not necessarily to solve the same problem I mentioned though).
Note2
Another note is that I think this can somewhat make "polymorphism" easier in Go. Struct embedding is like "inherence" in many ways, but not always. Suppose we have
We still need an interface type that contains the methods of
Base
if we want something that can hold either aBase
or aDerived
. And the proposedinterface { Base }
is such an interface.The text was updated successfully, but these errors were encountered: