结构体的嵌入类型


1、嵌入结构体1

packagemainimport"fmt"typePersonstruct{namestring}typeStudentstruct{classintpersonPerson//定义person类型为Person}funcmain(){s:=Student{1,Person{"xiaoming"}}fmt.Println("name:",s.person.name)//访问嵌入结构体的变量}//执行结果:name:xiaoming

2、嵌入结构体2

packagemainimport"fmt"typePersonstruct{namestring}typeStudentstruct{classintPerson//我们直接将Person引入到Student}funcmain(){s:=Student{1,Person{"xiaoming"}}fmt.Println("name:",s.name)//访问时可以直接访问s.name而不需要s.person.name}//执行结果:name:xiaoming

接口


1、定义接口

在go语言中,接口是定义了类型一系列方法的列表,如果一个类型实现了该接口所有的方法,那么该类型就符合该接口

packagemainimport"fmt"import"math"typeShapeinterface{area()float64}typeRectanglestruct{widthfloat64heightfloat64}typeCirclestruct{radiusfloat64}func(rRectangle)area()float64{returnr.height*r.width}func(cCircle)area()float64{returnmath.Pi*math.Pow(c.radius,2)}funcgetArea(shapeShape)float64{returnshape.area()}funcmain(){r:=Rectangle{20,10}c:=Circle{4}fmt.Println("RectangleArea=",getArea(r))fmt.Println("CircleArea=",getArea(c))}//执行结果:RectangleArea=200CircleArea=50.26548245743669

2、接口嵌入

packagemainimport"fmt"import"math"typeShapeinterface{area()float64}typeMultiShapeinterface{Shape//嵌入式}typeRectanglestruct{widthfloat64heightfloat64}typeCirclestruct{radiusfloat64}func(rRectangle)area()float64{returnr.height*r.width}func(cCircle)area()float64{returnmath.Pi*math.Pow(c.radius,2)}funcgetArea(shapeMultiShape)float64{//改为MultiShapereturnshape.area()}funcmain(){r:=Rectangle{20,10}c:=Circle{4}fmt.Println("RectangleArea=",getArea(r))fmt.Println("CircleArea=",getArea(c))}//执行结果:RectangleArea=200CircleArea=50.26548245743669//执行结果一致