概述:
第一种,在实例方法被调用时,会产生值复制
func (e Employee) String() string {}
第二种,不会进行内存拷贝,所以通常情况下推荐使用第二种
func (e *Employee) String1() string {}
代码测试:
type Employee struct {
Id string
Name string
Age int
} func (e Employee) String() string {
fmt.Printf("Address is %x \n", unsafe.Pointer(&e.Name))
return fmt.Sprintf("ID: %s-Name: %s-Age: %d", e.Id, e.Name, e.Age)
} func (e *Employee) String1() string {
fmt.Printf("Address is %x \n", unsafe.Pointer(&e.Name))
return fmt.Sprintf("ID:%s / Name: %s / Age: %d", e.Id, e.Name, e.Age)
} func TestStructOperations(t *testing.T) {
e := Employee{"0", "Bob", 20}
fmt.Printf("Address is %x \n", unsafe.Pointer(&e.Name))
t.Log(e.String()) fmt.Printf("Address is %x \n", unsafe.Pointer(&e.Name))
t.Log(e.String1())
}
测试结果:
可以看到使用第一种方式来创建方法时,会产生内存拷贝,造成内存空间浪费。