Interfaces

About

Interfaces are useful as contracts, to state what fields or methods a struct should follow.

struct can be seen as the implementation description of the object.

interface can be seen as generic contracts, that structs can "implement".

Creating

// Since it is not Uppercase, it is only available inside the package
type saver interface {
    state bool
    Save(int, string) error
}

Interfaces with only one method

It is a convention that if an interface has only one method, the interface's name will be that method + er.

Ex.: Save() would make the interface name to be saver.

type saver interface {
    Save() error
}

any interface

Similar to Typescript any type, you have a generic interface that accepts anything with interface{} or any.

func print(value interface{}) {}

func print(value any){}

Using it

func saveData(data saver) {
    ...
}

node = node.New()
todo = todo.New()

saveData(note.Save())
saveData(todo.Save())

Embedded interfaces

In the same way as struct you may embbed interface,

type saver interface {
    Save() error
}

type outputtable interface {
    saver
    Display()
}

Last updated