Link: https://play.golang.org/p/69I8PAuoAV
Extract:
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")
}
The printString(s)
function call when reaching case matches the case Stringer
part.
s
is of type *fakeString
not Stringer
.
Why does it match Stringer
.
I did a fmt.Println(reflect.TypeOf(str))
and it confirmed the type as *main.fakeString