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
Interfaces can have methods descriptions in them, as opposed to struct
that can only have the fields descriptions.
// 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
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
In Go you don't have to explicitly state that the structs Node
and Todo
have to implement saver
.
The struct just have to implement whatever the interface states.
In the example, since the structs have a Save()
method and state
field, it is enough.
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