Skip to content

Instantly share code, notes, and snippets.

@EthanHeilman
Created February 23, 2024 22:39
Show Gist options
  • Save EthanHeilman/6c4e78f3eaf1f1dba96f70aab17b73c8 to your computer and use it in GitHub Desktop.
Save EthanHeilman/6c4e78f3eaf1f1dba96f70aab17b73c8 to your computer and use it in GitHub Desktop.
Composition Example
import (
"testing"
"github.com/stretchr/testify/require"
)
type Fruit interface {
Size() string
Look() string
}
type Apple struct {
size string
}
func (a Apple) Look() string {
return a.size + "apple"
}
func (a Apple) Size() string {
return a.size
}
type DefaultOrange struct {
size string
}
func (d DefaultOrange) Look() string {
return d.size + "default-orange" // The default fruit is orange
}
type MediumOrange struct {
DefaultOrange
}
func (u MediumOrange) Size() string {
return u.size
}
func Fruitify(f Fruit) Fruit {
return f
}
func TestStructComposition(t *testing.T) {
apple := Apple{}
apple.size = "small"
appleInterface := Fruitify(apple)
require.Equal(t, appleInterface.Look(), "smallapple")
require.Equal(t, appleInterface.Size(), "small")
MediumOrange := MediumOrange{}
MediumOrange.size = "medium"
MediumOrangeInterface := Fruitify(MediumOrange)
require.Equal(t, MediumOrangeInterface.Look(), "mediumdefault-orange")
require.Equal(t, MediumOrangeInterface.Size(), "medium")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment