String()与GoString()
type Man struct { name string } func (m *Man) String() string { var buf bytes.Buffer buf.WriteString("My name is :" + m.name) return buf.String() } func (m *Man) GoString() string { var buf bytes.Buffer buf.WriteString("GoString:" + m.String()) return buf.String() } type WoMan struct { name string } func (m WoMan) String() string { return "My name is :" + m.name } func (m WoMan) GoString() string { return "GoString:" + m.String() }
func Test_split(t *testing.T) { var m Man m.name = "man" fmt.Println(m) fmt.Println(&m) fmt.Printf("%#v\n", m) fmt.Printf("%#v\n", &m) var wm WoMan wm.name = "woman" fmt.Println(wm) fmt.Println(&wm) fmt.Printf("%#v\n", wm) fmt.Printf("%#v\n", &wm) }
输出结果:
{man} My name is :man mystring.Man{name:"man"} GoString:My name is :man My name is :woman My name is :woman GoString:My name is :woman GoString:My name is :woman
结论:
优先选择如下方式定义,recever为值类型 type WoMan struct { name string } func (m WoMan) String() string { return "My name is :" + m.name } func (m WoMan) GoString() string { return "GoString:" + m.String() }