Back to questions
JuniorTheoryCommon
What does the program print?
package main
import "fmt"
type Temp struct{ C int }
func (t *Temp) String() string { return fmt.Sprintf("%d°C", t.C) }
func main() {
t := Temp{C: 21}
fmt.Println(t, &t)
}{21} 21°C
- Expecting
21°C 21°C:Stringhas a pointer receiver, so only*Tempimplementsfmt.Stringer, and the valuetprints as its plain fields. - Expecting the pointer to print as
&{21}:&thas the type*Temp, which has theStringmethod, sofmtcalls it and prints21°C.
- How would you change the method so that
fmt.Println(t)also prints21°C? - Why can you call
t.String()on the variablet, yettdoes not implementfmt.Stringer?