go语言行为(方法)的两种定义差别

2023-02-22,,

概述:

go在定义方法时,有如下两种表示形式:

第一种,在实例方法被调用时,会产生值复制

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

测试结果:

可以看到使用第一种方式来创建方法时,会产生内存拷贝,造成内存空间浪费。

go语言行为(方法)的两种定义差别的相关教程结束。

《go语言行为(方法)的两种定义差别.doc》

下载本文的Word格式文档,以方便收藏与打印。