结构体的定义与使用 使用type定义结构体。
1 2 3 4 5 6 7 8 9 10 11 type structName struct { property1 int property2 int } var structName substancestructName.property1 structName.property2
例子如下,
1 2 3 4 5 6 7 8 9 10 11 12 13 type person struct { name string age int } func main () { var sagume person sagume.name="sagume" fmt.Println(sagume.name) }
类的表示与继承 1 2 3 4 5 6 7 8 9 10 11 12 13 type person struct { name string age int } func (this person) GetName(){ fmt.Println("Name=" ,person.name) }
其中,this person 为结构体实例的拷贝,若需修改属性,添加指针。
注意,若类的属性或方法首字母大写,则表示该属性能对外访问,即对于Java中public属性。否则只能对类的内部访问,即对于Java中的private属性。
例子如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 func (this person) show(){ fmt.Println(this.name) } func (this *person) setName(newName string ){ this.name=newName } func main () { var sagume person sagume.name="sagume" sagume.setName("Kishin_Sagume" ) sagume.show() }
在子类结构体中,输入父类结构体,表示继承。
1 2 3 4 5 6 7 8 9 10 11 type animals struct { weight int height int } type sheep struct { animals ... }
类的多态与接口 Interface本质上为指针,接入该接口的类需要实现该接口定义的方法。
实现例子如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 type AnimalsIF interface { sleep() GetColor() string GetType() string } type Cat struct { color string Type string } func (this *Cat) GetColor() string { fmt.Println(this.color) return this.color } func (this *Cat) GetType() string { fmt.Println(this.Type) return this.Type } func main () { var mimi AnimalsIF mimi=Cat{"white" ,"cat" } mimi.GetColor() mimi.GetType() }
也可以直接实现接口方法。
1 2 3 4 5 6 7 8 9 func HowtoSleep (animals AnimalsIF) { animals.sleep() fmt.Println(animals.GetColor(),animals.GetType()) } func main () { mimi:=Cat{"white" ,"cat" } HowtoSleep(&mimi) }
注意!接口本质上为指针,在实现接口方法时,记得传入变量地址。
总结:
父类(接口)本质上是一个指针
子类继承父类,需要实现父类所有的接口方法
父类指针指向子类的具体数据,调用父类方法即调用对应子类的方法。
空接口与类型断言机制 interface{}为空接口,例如 int, string, float32等皆实现了interface{}这一通用接口。
对通用接口使用”类型断言“,可以查询该接口实现的类型,例子如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 func myFunc (arg interface {}) { fmt.Println("Func is called" ) fmt.Println(arg) value,ok:=arg.(string ) if !ok{ fmt.Println("arg is not string" ) fmt.Printf("type of value: %T" , value) }else { fmt.Println("type is string" ) } } func main () { myFunc("good" ) }