Back to questions
JuniorTheoryCommon
What does the program print?
package main
import "fmt"
type Celsius float64
func (c Celsius) String() string { return fmt.Sprint(float64(c)) + "°C" }
func main() {
t := Celsius(21)
fmt.Println(t, float64(t))
}21°C 21
- Expecting
21 21:Celsiushas aString() stringmethod, so it satisfiesfmt.Stringer, andfmt.Printlnprintstby calling that method. - Expecting
21°Ctwice:float64(t)is a plainfloat64, which has noStringmethod, sofmtprints the bare number21.
- Why does
Stringconvertctofloat64before passing it tofmt.Sprint? - Would
fmt.Printlnstill callStringif the method had the receiver(c *Celsius)?