在 go 中撰写可器重编码必须:应用接口定义方式,便于不同种类能够实现他们。将另一个种类的字段嵌入到当前类型中,以组成种类并器重特点。定义函数,并把它申明为高层函数或添加到包中。
怎样在 Go 中撰写可重用的编码并实现代码复用
可器重代码是当代编程中非常重要的一部分,它允许开发者建立模块化与可维护的应用程序。Go 语言提供了强大的特点,能够帮助你撰写可重用的编码。
插口(Interfaces)
接口定义了一组方式,一切种类都可以实现他们。根据使用插口,你可以轻松地建立通用编码,可以和各种类型一起工作。
实例:
typeShapeinterface{
Area()float64
Perimeter()float64
}
置入(Embedding)
置入允许你将另一个种类的字段嵌入到当前类型中。这允许你组成种类并器重他们的特点。
实例:
typePersonstruct{
Namestring
}
typeEmployeestruct{
Person
Salaryfloat64
}
函数(Functions)
使用函数是促进可器重代码的另一种方法。能通过把它们申明为高层函数或添加到包中来定义函数。
实例:
funcCalculateArea(sShape)float64{
returns.Area()
}
实战案例
考虑一个必须测算各种形状(如环形、方形和三角形)面积的应用程序。应用上面介绍的技术,我们能撰写可重用的编码去处理各种形状种类:
typeCirclestruct{
Radiusfloat64
}
func(cCircle)Area()float64{
returnmath.Pic.Radiusc.Radius
}
typeRectanglestruct{
Lengthfloat64
Widthfloat64
}
func(rRectangle)Area()float64{
returnr.Lengthr.Width
}
typeTrianglestruct{
Basefloat64
Heightfloat64
}
func(tTriangle)Area()float64{
return0.5t.Baset.Height
}
funcmain(){
circle:=Circle{Radius:5}
rectangle:=Rectangle{Length:10,Width:5}
triangle:=Triangle{Base:5,Height:10}
areas:=[]float64{
CalculateArea(circle),
CalculateArea(rectangle),
CalculateArea(triangle),
}
for_,area:=rangeareas{
fmt.Println(area)
}
}
根据使用插口、置入和函数,大家创立了可重用的编码,能够为应用程序的不同部分快速地测算不同形状的面积。
以上就是怎样在golang中撰写可器重编码并实现代码复用?的详细内容,大量请关注其他类似文章!