Go学习笔记(三):接口
2020-04-12 14:38:51摘要:封装数据与行为 结构体定义 type Employee struct { Id string Name string Age int } 实例创建及初始化 e := Employee{0, Bob, 20} e1 := Employee{Name: Mike, Age: 30} e2 := new(Employee) //注意这⾥返回的引⽤/指针,相当于 e := Employee{} e2.Id = “2 //与其他主要编程语⾔的差异:通过实例的指针访问成员不需要使⽤- e2.Age = 22 e2.Name = “Rose 行为(方法)定义 //第⼀种定义⽅式在实例对应⽅法被调⽤时,实例的成员会进⾏值复制 func (e Employee) String() string { return fmt.Sprintf(ID:%s-Name:%s-Age:%d, e.Id, e.Name, e.Age) } //通常情况下为了避免内存拷⻉我们使⽤第⼆种定义⽅式 func (e *Employee) String() string { return fmt.Sprintf(ID:%s/Name:%s/Age:%d, e.Id, e.Name, e.Age) } type Employee struct { Id string Name string Age int } func (e Employee) String() string { //这里传递的是类型 fmt.Printf(Address is %x, unsafe.Pointer(e.Name)) } func TestStructOperations(t *testing.T) { e := Employee{0, Bob, 20} fmt.Printf(Address is %x, unsafe.Pointer(e.Name)) t.Log(e.String()) //Address is c000068520 Address is c000068550 } 可以看到上面测试程序调用String方法时传递的是类型,log得到的是2不同的地址,如果改成传递地址呢? func (e Employee) String() …… 阅读全文
