Skip to content

Instantly share code, notes, and snippets.

@erikcorry
Created April 16, 2021 15:52
Show Gist options
  • Save erikcorry/3c23d88ce3afe5f8d23cd446f0a9f2e9 to your computer and use it in GitHub Desktop.
Save erikcorry/3c23d88ce3afe5f8d23cd446f0a9f2e9 to your computer and use it in GitHub Desktop.
package main
// Existing classes we can't extend because they are
// in a different package.
type Foo struct {
Name string
}
type Bar struct {
Name string
}
type Baz struct {
Name string
}
// These new types are introduced so we can add
// methods too Foo, Bar, and Baz.
type MyFoo Foo
type MyBar Bar
type MyBaz Baz
// Add the new method to the new type so it implements Named.
func (foo *MyFoo) GetName() string {
return foo.Name
}
// Add the new method to the new type so it implements Named.
func (bar *MyBar) GetName() string {
return bar.Name
}
// Add the new method to the new type so it implements Named.
func (baz *MyBaz) GetName() string {
return baz.Name
}
// Implemented by the new type.
type Named interface {
GetName() string
}
func main() {
var slice []Named
// We have to wrap the old types in the new ones. This takes
// a copy of the struct.
my_foo := MyFoo(Foo{Name: "fooname"})
my_bar := MyBar(Bar{Name: "barname"})
my_baz := MyBaz(Baz{Name: "bazname"})
// Because they are wrapped, they implement the new
// interface.
slice = append(slice, &my_foo)
slice = append(slice, &my_bar)
slice = append(slice, &my_baz)
for _, named := range slice {
println(named.GetName())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment