定义结构体
package encapsulation
import "testing"
type Employee struct {
Id string
Age int64
Name string
}
func TestCreateEmployee(t *testing.T){
e := Employee{"0",20,"leo"}
e1 := Employee{Name:"ioe"}
e2 := new(Employee) //指针类型
e2.Id = "20"
e2.Name = "Cherry"
e2.Age = 30
t.Log(e)
t.Log(e1)
t.Log(*e2)
}
避免内存拷贝
package encapsulation
import (
"fmt"
"testing"
"unsafe"
)
type Employee struct {
Id string
Age int64
Name string
}
func TestCreateEmployee(t *testing.T){
e := Employee{"0",20,"leo"}
e1 := Employee{Name:"ioe"}
e2 := new(Employee)
e2.Id = "20"
e2.Name = "Cherry"
e2.Age = 30
t.Log(e)
t.Log(e1)
t.Log(*e2)
}
//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) 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 TestStructOperations(t *testing.T){
e := Employee{"1",20,"Bob"}
e.String()
fmt.Printf("Address is %x\n",unsafe.Pointer(&e.Name))
}