结构体的嵌入类型
1、嵌入结构体1
packagemainimport"fmt"typePersonstruct{ namestring}typestudentstruct{ classint personPerson//定义person类型为Person}funcmain(){ s:=Student{1,Person{"xiaoming"}} fmt.Println("name:",s.person.name)//访问嵌入结构体的变量}//执行结果:name:xiaoming
2、嵌入结构体2
packagemainimport"fmt"typePersonstruct{ namestring}typestudentstruct{ classint Person//我们直接将Person引入到Student}funcmain(){ s:=Student{1,s.name)//访问时可以直接访问s.name而不需要s.person.name}//执行结果:name:xiaoming
1、定义接口
在go语言中,接口是定义了类型一系列方法的列表,如果一个类型实现了该接口所有的方法,那么该类型就符合该接口
packagemainimport"fmt"import"math"typeShapeinterface{ area()float64}typeRectanglestruct{ wIDthfloat64 heightfloat64}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{ wIDthfloat64 heightfloat64}typeCirclestruct{ radiusfloat64}func(rRectangle)area()float64{ returnr.height*r.wIDth}func(cCircle)area()float64{ returnmath.Pi*math.Pow(c.radius,2)}funcgetArea(shapeMultiShape)float64{//改为MultiShape returnshape.area()}funcmain(){ r:=Rectangle{20,getArea(c))}//执行结果:RectangleArea=200CircleArea=50.26548245743669//执行结果一致总结
以上是内存溢出为你收集整理的golang 结构体的嵌入类型和接口全部内容,希望文章能够帮你解决golang 结构体的嵌入类型和接口所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)