一、结构体的定义
//结构定义 type Employee struct { Id string Name string Age int }
二、实例的创建
//初始化结构体 func TestCreateEmployeeObj(t *testing.T) { e := Employee{"0", "bob", 20} e1 := Employee{Name: "MIke", Age: 30} //返回指针 e2 := new(Employee) e3 := Employee{} e.Name = "ccc" e2.Id = "2" e2.Age = 22 t.Log(e) t.Log(e1) t.Log(e1.Id) t.Log(e2) t.Log(e3) t.Logf("e is %T", e) t.Logf("e2 is %T", e2) }
三、结构体行为定义
//定义结构体的行为,实例访问 func (e Employee) String() string { fmt.Printf("String-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) StringTo() string { fmt.Printf("StringTo-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()) t.Log(e.StringTo()) }
四、完整代码
package encapsulation 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: 30} //返回指针 e2 := new(Employee) e3 := Employee{} e.Name = "ccc" e2.Id = "2" e2.Age = 22 t.Log(e) t.Log(e1) t.Log(e1.Id) t.Log(e2) t.Log(e3) t.Logf("e is %T", e) t.Logf("e2 is %T", e2) } //定义结构体的行为,实例访问 func (e Employee) String() string { fmt.Printf("String-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) StringTo() string { fmt.Printf("StringTo-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()) t.Log(e.StringTo()) }
=== RUN TestCreateEmployeeObj String-Address is c00007c880 encap_test.go:26: ID:0-Nameccc-age:20 String-Address is c00007c940 encap_test.go:27: ID:-NameMIke-age:30 encap_test.go:28: String-Address is c00007c970 encap_test.go:29: ID:2-Name-age:22 String-Address is c00007c9d0 encap_test.go:30: ID:-Name-age:0 encap_test.go:31: e is encapsulation.Employee encap_test.go:32: e2 is *encapsulation.Employee --- PASS: TestCreateEmployeeObj (0.00s) === RUN TestStructOPerations Address is c00007ca90 String-Address is c00007cac0 encap_test.go:49: ID:0-Namebob-age:20 StringTo-Address is c00007ca90 encap_test.go:50: ID:0-Namebob-age:20 --- PASS: TestStructOPerations (0.00s) PASS