Created
February 23, 2024 22:39
-
-
Save EthanHeilman/6c4e78f3eaf1f1dba96f70aab17b73c8 to your computer and use it in GitHub Desktop.
Composition Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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