Skip to content

Instantly share code, notes, and snippets.

@daniellowtw
Last active March 31, 2016 10:20
Show Gist options
  • Select an option

  • Save daniellowtw/e2ff380a14e00cf5f6784cc7f7da6859 to your computer and use it in GitHub Desktop.

Select an option

Save daniellowtw/e2ff380a14e00cf5f6784cc7f7da6859 to your computer and use it in GitHub Desktop.
Experiments with interface embedding
package main
import "testing"
type A interface {
x(key interface{}) interface{}
}
type B struct {
A
y *AImpl
}
type AImpl struct{}
func (c *AImpl) x(key interface{}) interface{} {
return "bar"
}
type C struct {
A
}
func (c *C) x(key interface{}) interface{} {
return "foo"
}
func TestEmbeddedInterfaceWorks(t *testing.T) {
defer assertNoPanic(t)
c := &C{}
c.x(1)
}
func TestEmbeddedInterfaceFailsWithEmbeddedAccessWhenNotDefined(t *testing.T) {
defer assertPanic(t)
c := &C{}
c.A.x(1)
}
func TestEmbeddedInterfaceWorksWithEmbeddedAccessIsDefined(t *testing.T) {
defer assertNoPanic(t)
c := &C{}
c.A = &AImpl{}
c.A.x(1)
}
func TestFieldsDoesNotImplementEmbeddedInterface(t *testing.T) {
defer assertPanic(t)
b := &B{y: &AImpl{}}
b.x(1)
}
func TestFieldsInterfaceWorks(t *testing.T) {
defer assertNoPanic(t)
b := &B{y: &AImpl{}}
b.y.x(1)
}
func assertPanic(t *testing.T) {
if err := recover(); err != nil {
return
}
t.Fail()
}
func assertNoPanic(t *testing.T) {
if err := recover(); err != nil {
t.Fail()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment