I’m new with Golang and I’ve started to read the book by A. Donovan, and I have a question in the end of one of chapters. He describes type declarations and type’s methods.
And I don’t understand why I get different results with the same call function Printf and Println?
So, we have the example
type Celsius float64
func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
c := FToC(212.0)
and have different calls functions of fmt package
fmt.Println(c.String()) // "100°C"
fmt.Printf("%v\n", c) // "100°C"; no need to call String explicitly
fmt.Printf("%s\n", c) // "100°C"
fmt.Println(c) // "100°C"
fmt.Printf("%g\n", c) // "100"; does not call String
fmt.Println(float64(c)) // "100"; does not call String]]
The function FToC converts temperature from two scales if it’s matter.
Printf and Println have different operands in both cases, but I’m not sure this is the answer. I have read about Stringer interface, but, as I understand, the entire package fmt looks for the method from this interface and prints values according to instructions from that. Then why does one method from fmt call String and another method don’t?
Alexandr is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2