I don't understand at which point an Interface method is being called. I'm looking at the following example from the Go Tour:
package main
import "fmt"
type Person struct {
Name string
Age int
}
func (p Person) String() string {
return fmt.Sprintf("%v (%v years)", p.Name, p.Age)
}
func main() {
a := Person{"Arthur Dent", 42}
z := Person{"Zaphod Beeblebrox", 9001}
fmt.Println(a, z)
}
Problem:
I understand that the func (p Person)
receives the String()
method and that it returns the string
I want to display. But the fmt.Println
in the main()
method has to call String()
at some point, right?
I had a look at the source of fmt
in godoc, but I still cannot figure it out!
Another example:
If I add my own interface, lets say Stringer2
with a method called String2()
and then create a func (p Person) String2() {....}
.
How does String()
get executed by fmt.Println
, but String2()
not?