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

Go笔记二(Interfaces)

发布时间:2020-12-16 18:52:33 所属栏目:大数据 来源:网络整理
导读:An Introduction To Programming In Go 读书笔记 -- 9 Structs and Interfaces - Interfaces packagemainimport("fmt""math")funcdistance(x1,y1,x2,y2float64)float64{a:=x2-x1b:=y2-y1returnmath.Sqrt(a*a+b*b)}typeCirclestruct{x,y,rfloat64}func(c*Circ

An Introduction To Programming In Go 读书笔记

-- 9 Structs and Interfaces - Interfaces


packagemain

import(
"fmt"
"math"
)
funcdistance(x1,y1,x2,y2float64)float64{
a:=x2-x1
b:=y2-y1
returnmath.Sqrt(a*a+b*b)
}

typeCirclestruct{
x,y,rfloat64
}
func(c*Circle)area()float64{
returnmath.Pi*c.r*c.r
}

typeRectanglestruct{
x1,y2float64
}
func(r*Rectangle)area()float64{
l:=distance(r.x1,r.y1,r.x1,r.y2)
w:=distance(r.x1,r.x2,r.y1)
returnl*w
}

typeShapeinterface{
area()float64
}
functotalArea(shapes...Shape)float64{
varareafloat64
for_,s:=rangeshapes{
area+=s.area()
}
returnarea
}

typeMultiShapestruct{
shapes[]Shape
}
func(m*MultiShape)area()float64{
varareafloat64
for_,s:=rangem.shapes{
area+=s.area()
}
returnarea
}

funcmain(){
c:=Circle{2,2,10}
fmt.Println(c.area())
r:=Rectangle{1,1,2}
fmt.Println(r.area())
t:=totalArea(&c,&r)
fmt.Println(t)

m:=new(MultiShape)
m.shapes=append(m.shapes,&c)
m.shapes=append(m.shapes,&r)
m.shapes=append(m.shapes,&r)
fmt.Println(m.area())

}

(编辑:李大同)

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

    推荐文章
      热点阅读