package obj
import (
"fmt"
"testing"
"unsafe"
)
// 数据的定义
type Employee struct{
Id string
Name string
Age int
}
func TestCreateEmployeeObj(t *testing.T){
e := Employee{"0", "Bob", 20}
e1 := Employee{Name:"Mike", Age:18}
e2 := new(Employee)
e2.Id = "2"
e2.Age = 22
e2.Name = "Rose"
t.Log(e)
t.Log(e1)
t.Log(e2)
t.Logf("e is %T", e)
t.Logf("e2 is %T", e2)
}
// 行为、方法的定义
func (e Employee) String() string{ // 空间复制大浪费
fmt.Printf("Addres 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) String2() string{
fmt.Printf("Addres is %x\n", unsafe.Pointer(&e.Name))
return fmt.Sprintf("ID:%s-Name:%s-Age:%d", e.Id, e.Name, e.Age)
}
func TestStruceOperations(t *testing.T){
e := Employee{"0", "Bob", 20}
//e := &Employee{"0", "Bob", 20}
t.Log(e.String()) // 这种方法,会复制,地址变化了,浪费空间
//t.Log(e.String2()) // 这种方法地址不会改变,对象直接进去。
fmt.Printf("Addres is %x\n", unsafe.Pointer(&e.Name))
}