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()) }