面试题答案
一键面试Go语言接口使用的两个主要优点
- 解耦代码依赖:接口使得不同模块之间通过抽象的接口进行交互,而不是具体的实现。这样可以降低代码之间的耦合度,提高代码的可维护性和可扩展性。例如,一个支付系统可能有多种支付方式(如微信支付、支付宝支付),通过定义一个支付接口,支付系统的核心逻辑只依赖于这个接口,而不关心具体是哪种支付方式的实现,后续添加新的支付方式也不会影响核心逻辑。
- 实现多态性:Go语言虽然没有传统面向对象语言那种基于类继承的多态,但通过接口可以轻松实现多态。不同类型只要实现了相同的接口,就可以在相同的逻辑中以统一的方式处理,增加代码的灵活性和复用性。
示例代码实现多态性
package main
import "fmt"
// 定义一个形状接口
type Shape interface {
Area() float64
}
// 定义圆形结构体并实现Shape接口
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}
// 定义矩形结构体并实现Shape接口
type Rectangle struct {
Width float64
Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
// 计算多个形状面积总和的函数,接受一个Shape接口类型的切片
func TotalArea(shapes []Shape) float64 {
var total float64
for _, shape := range shapes {
total += shape.Area()
}
return total
}
func main() {
circles := []Circle{
{Radius: 5},
{Radius: 3},
}
rectangles := []Rectangle{
{Width: 4, Height: 6},
{Width: 2, Height: 8},
}
var shapes []Shape
for _, circle := range circles {
shapes = append(shapes, circle)
}
for _, rectangle := range rectangles {
shapes = append(shapes, rectangle)
}
total := TotalArea(shapes)
fmt.Printf("Total area of all shapes: %.2f\n", total)
}
在上述代码中,Circle
和Rectangle
结构体都实现了Shape
接口的Area
方法。TotalArea
函数接受一个Shape
接口类型的切片,这样无论是圆形还是矩形都可以统一处理,体现了多态性。