加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 18:18:25 所属栏目:大数据 来源:网络整理
导读:结构体的嵌入类型 1、嵌入结构体1 packagemainimport"fmt"typePersonstruct{namestring}typeStudentstruct{classintpersonPerson//定义person类型为Person}funcmain(){s:=Student{1,Person{"xiaoming"}}fmt.Println("name:",s.person.name)//访问嵌入结构体

结构体的嵌入类型


1、嵌入结构体1

packagemain

import"fmt"

typePersonstruct{
	namestring
}

typeStudentstruct{
	classint
	personPerson//定义person类型为Person
}


funcmain(){
	s:=Student{1,Person{"xiaoming"}}
	fmt.Println("name:",s.person.name)//访问嵌入结构体的变量

}
//执行结果:
name:xiaoming

2、嵌入结构体2

packagemain

import"fmt"

typePersonstruct{
	namestring
}

typeStudentstruct{
	classint
	Person//我们直接将Person引入到Student
}


funcmain(){
	s:=Student{1,s.name)//访问时可以直接访问s.name而不需要s.person.name

}
//执行结果:
name:xiaoming

接口


1、定义接口

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

packagemain

import"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=200
CircleArea=50.26548245743669

2、接口嵌入

packagemain

import"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=200
CircleArea=50.26548245743669//执行结果一致

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读