skip to content
Alvin Lucillo

Go composition with interfaces

/ 2 min read

πŸ’» Tech

You can combine multiple interfaces into one interface in what we call composition like the ViewerEncrypter interface below. ViewerEncrypter interface object can accept anything that implements the functions defined in the individual interfaces. In the example below, we assigned bike concrete type to ve, a ViewerEncrypter. Not only that, we can assign an interface object to another. In the example below, we assigned ve to v, an object of type Viewer interface. This is possible because Viewer interface requires View() function, and ve fulfills that. With that, ve has been implicitly converted into Viewer, losing the Encrypter part of it, which is shown in the error when we assign v back to ve.

package main

import "fmt"

type Viewer interface {
	View()
}

type Encrypter interface {
	Encrypt()
	Decrypt()
}

type ViewerEncrypter interface {
	Viewer
	Encrypter
}

type app struct{}

func (app) View()    {}
func (app) Encrypt() {}
func (app) Decrypt() {}

func main() {
	fmt.Println("Hello, δΈ–η•Œ")

	var v Viewer
	var ve ViewerEncrypter

	app := app{}

	ve = app
	v = ve

	ve = v // ./prog.go:38:7: cannot use v (variable of type Viewer) as ViewerEncrypter value in assignment: Viewer does not implement ViewerEncrypter (missing method Decrypt)
}

Go playground: https://go.dev/play/p/oxsxIr1NC74