I'm reading "Go Bootcamp" and there is an example in the Chapter 3, page 20 I cannot understand. In this example, in the line printString(s), s is a variable of type fakeString, but in the switch, enters in the "Stringer" case. I'm trying to understand how is this possible. Any help would be appreciated.
The code is:
package main
import "fmt"
type Stringer interface {
String() string
}
type fakeString struct {
content string
}
// function used to implement the Stringer interface
func (s *fakeString) String() string {
return s.content
}
func printString(value interface{}) {
switch str := value.(type) {
case string:
fmt.Println(str)
case Stringer:
fmt.Println(str.String())
}
}
func main() {
s := &fakeString{"Ceci n'est pas un string"}
printString(s)
printString("Hello, Gophers")
}
Because the fakeString is a different type than string, but it implements Stringer interface. Every type with given function implements the type. The fakeString contains the String() func so it also implements Stringer interface. This is some kind of fundamental stones of Go.
Check the built-in libs for Reader interface, it is usually given as an example for this.