golang 结构体的嵌入类型和接口

golang 结构体的嵌入类型和接口,第1张

概述结构体的嵌入类型 1、嵌入结构体1 package mainimport "fmt"type Person struct { name string}type Student struct { class int person Person         //定义person 类型为Person}func main(){ s := Student{1,Person{

结构体的嵌入类型


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 结构体的嵌入类型和接口所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1279456.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存