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()
}

  

 

posted @ 2022-03-22 20:24  siduoge2  阅读(42)  评论(0编辑  收藏  举报