Go 行为的定义与实现 电脑版发表于:2021/1/30 16:03 ![go数据类型](https://img.tnblog.net/arcimg/hb/0dd243ae49394f12beed84237bfee1a3.jpg "go数据类型") >#Go 行为的定义与实现 [TOC] tn>在Go语言中其实是不可以实现继承的,但网上有继承相关但方式。所以Go既可以算得上面向对象,也算不上面向对象。 实例的创建以及初始化 ------------ ```go package encap import "testing" type Employee struct { Id string Name string Age int } func TestCreateEmployeeObj(t *testing.T) { e := Employee{"0", "Bob", 19} e1 := Employee{Name: "Bob", Age: 20} e2 := new(Employee) // 注意这里返回的引用/指针 相当于e := &Employee{} e2.Name = "AiDaSi" // 与其他主要编程语言的主要差距是,通过实例指针访问成员不需要-> e2.Id = "1" e2.Age = 19 t.Logf("e.Id: %s e.Name: %s e.Age: %d", e.Id, e.Name, e.Age) t.Logf("e1.Id: %s e1.Name: %s e1.Age: %d", e1.Id, e1.Name, e1.Age) t.Logf("e2.Id: %s e2.Name: %s e2.Age: %d", e2.Id, e2.Name, e2.Age) } ``` ![](https://img.tnblog.net/arcimg/hb/e6afb05403584c44848dfb4c172e30d3.png) tn>如果想获取它的类型的话,我们从下图发现`e1`是实例的对象类型,`e2`是指针类型。 ```go // 使用%T获取该类型 t.Logf("e1 is %T", e1) t.Logf("e2 is %T", e2) ``` ![](https://img.tnblog.net/arcimg/hb/9bae3b25a8374502812088ad2e894e23.png) 行为方法的定义 ------------ tn>相当于c#对类对扩展方法一样 ```go // 相当于扩展方法 // 通过实例去请求的方法 func (e Employee) String() string { return fmt.Sprintf("e type: %T e.Id: %s e.Name: %s e.Age: %d Indicator: %x", e, e.Id, e.Name, e.Age, unsafe.Pointer(&e.Id)) } // 通过指针去请求的方法 func (e *Employee) IndicatorString() string { return fmt.Sprintf("e type: %T e.Id: %s e.Name: %s e.Age: %d Indicator: %x", e, e.Id, e.Name, e.Age, unsafe.Pointer(&e.Id)) } func TestBeHavior(t *testing.T) { e := Employee{"1", "Bob", 19} // 获取实例指针 t.Logf("Init: %x", unsafe.Pointer(&e.Id)) t.Logf(e.String()) t.Logf(e.IndicatorString()) } ``` tn>在这里我们一般使用第二种方式,因为是使用的同一个指针而少做类一次实例的复制 ![](https://img.tnblog.net/arcimg/hb/be15020d2a6a4b0f94e974e6ea035c89.png)