implementing an interface
tags: learning programming go
content
- an interface is a collection of function signatures
- could be one or more function signatures (or none!)
what does it mean when a type implements an interface?
- it means that this type has methods that satisfy all function signatures in an interface
the below Book and Count are completely different things, but they both satisfy (or implement) fmt.Stringer interface
type Stringer interface {
String() string
}
type Book struct { // a Book type that has two data fields
Title string
Author string
}
func (b Book) String() string {
return fmt.Sprintf("%s - %s", b.Title, b.Author)
}
type Count int // a Count type that's only an int
func (c Count) String() string {
return strconv.Itoa(int(c))
}