考虑以下代码。第一个函数是 MessageStr 类型的接收器方法。为什么fmt.Println(msgstr)执行第一个方法而不调用方法 as fmt.Println(msgstr.String())。还有为什么fmt.Println(msgint32)不执行第二种方法。
package main
import (
"fmt"
)
type MessageStr string
type MessageInt32 int32
func (msgs MessageStr) String() string {
return string("<<" + msgs + ">>")
}
func (msgi MessageInt32) Int32() int32 {
return int32(msgi * 2)
}
func main() {
msgstr := MessageStr("Mastering Go")
// why this outputs <<Mastering Go>>
// without calling the String() method
fmt.Println(msgstr)
msgint32 := MessageInt32(11)
// why this doesn't output 11*2 = 22
fmt.Println(msgint32)
fmt.Println(msgint32.Int32())
}
猛跑小猪
相关分类