Interface Composition
Demonstrating Interface Composition in Go
One cool feature of Go is that it lets you compose interfaces using other interfaces. The prototypical example of this is the ReadWriter, which is composed of the Reader interface and the Writer interface.
Below is an example of a toy program that defines a UserStorer interface and an ItemStorer interface, then a Storer interface that is composed of these interfaces
Define User Stuff
package main
import (
"encoding/json"
"fmt"
)
//create type
type User struct {
string
Name int
Age }
//create interface
type UserStorer interface {
(users []*User, user *User) []*User
AddUser}
//define an empty struct that will implement interface
type ustore struct{}
//constructor
func NewUserStore() UserStorer {
return &ustore{}
}
func (us ustore) AddUser(users []*User, user *User) []*User {
= append(users, user)
users
return users
}
Define Item Stuff
//define type
type Item struct {
string
Name string
Usage }
//define interface
type ItemStorer interface {
(items []*Item, item *Item) []*Item
AddItem}
//define empty struct that will implement interface
type istore struct{}
//define constructor
func NewItemStore() ItemStorer {
return &istore{}
}
//define add method
func (is istore) AddItem(items []*Item, item *Item) []*Item {
= append(items, item)
items
return items
}
Define Storer Stuff
type Storer interface {
UserStorer
ItemStorer}
type myStore struct {
UserStorer
ItemStorer}
func NewStorer(us UserStorer, is ItemStorer) Storer {
:= &myStore{
s : us,
UserStorer: is,
ItemStorer}
return s
}
Create Simple Program
func main() {
:= NewUserStore()
us := NewItemStore()
is
:= NewStorer(us, is)
s
var items []*Item
var users []*User
:= &User{
u : "Eric",
Name: 34,
Age}
:= &Item{
i : "Phone",
Name: "texting",
Usage}
= s.AddItem(items, i)
items = s.AddUser(users, u)
users
//embed to json
, _ := json.Marshal(items)
ji, _ := json.Marshal(users)
ju
//print out results
.Println(string(ji))
fmt.Println(string(ju))
fmt}