golang 结构体的嵌入类型和接口
结构体的嵌入类型
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//执行结果一致
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。