I really really do not understand why fmt.Println(“hahoooExecuting SXtring() for CustomType!”) gets executed…
Looks like somehow, String() gets executed… but why? I have tried to look at Println documentation to see if anything implements them and using custom string as receiver but I did not see any… What am I missing? Please point me to right direction as I thought I start to understand golang but this just completely destroyed me and have me stuck here… Please help. I am desperate to understand this.
Stringer is implemented by any value that has a String method, which defines the “native” format for that value. The String method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as Print.
Thanks for this and helped a lot. However, Having this knowledge, I still cannot connect to why Println is using String method… I do not see that in the doc
I continue to read the documentation and still not clear(not your fault @petrus)… It is just my lack of understanding on golang but this is driving me crazy.
I get that Stringer is an interface which any that implements String func, it is eligible… But I fail to see how printer such as fmt.Println is suppose to implements func String() Where in the doc says that ? From this particular example, Is this because type is string and matches “String() string” part from the Stringer interface definition?
And I just tried below to see if the string theory that I am having it in my head is correct and it is not… (I somehow thought because return type is string, it’s matching it)
type Person struct {
Age int
}
func (p Person) String() string {
fmt.Println("this is crazy")
return fmt.Sprintf(" (%v years)", p.Age)
}
func main() {
a := Person{ 42}
z := Person{9001}
fmt.Println(a, z)
}
Stringer is implemented by any value that has a String method, which defines the “native” format for that value. The String method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as Print.
type Stringer interface {
String() string
}
fmt.Println is an unformatted printer. Person satisfies the Stringer interface, it has a String() string method. Therefore, fmt calls the Person String() method with a Person receiver to return the string to print for any Println type Person operand (argument).
package main
import "fmt"
type Person struct {
Age int
}
func (p Person) String() string {
return fmt.Sprintf("%v years old", p.Age)
}
func main() {
p := Person{42}
fmt.Println(p)
}