MST

星途 面试题库

面试题:Go语言中如何通过接口增强代码复用性之基础实现

请举例说明在Go语言中,如何定义一个接口,并通过结构体实现该接口,以此来展示代码复用的基本操作。假设你有一个图形绘制的场景,定义一个Shape接口,包含Area方法,然后实现Circle和Rectangle结构体来实现这个接口,并在主函数中展示如何通过接口来复用代码计算不同图形的面积。
32.8万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import (
    "fmt"
)

// 定义Shape接口,包含Area方法
type Shape interface {
    Area() float64
}

// Circle结构体
type Circle struct {
    radius float64
}

// Circle实现Shape接口的Area方法
func (c Circle) Area() float64 {
    return 3.14 * c.radius * c.radius
}

// Rectangle结构体
type Rectangle struct {
    width  float64
    height float64
}

// Rectangle实现Shape接口的Area方法
func (r Rectangle) Area() float64 {
    return r.width * r.height
}

func main() {
    // 创建Circle和Rectangle实例
    circle := Circle{radius: 5}
    rectangle := Rectangle{width: 4, height: 6}

    // 创建一个Shape类型的切片,里面包含Circle和Rectangle实例
    shapes := []Shape{circle, rectangle}

    // 遍历切片,通过接口调用Area方法计算不同图形的面积
    for _, shape := range shapes {
        fmt.Printf("The area of the shape is: %f\n", shape.Area())
    }
}

在上述代码中:

  1. 首先定义了Shape接口,包含Area方法。
  2. 然后分别定义了CircleRectangle结构体,并为它们实现了Shape接口的Area方法。
  3. main函数中,创建了CircleRectangle的实例,并将它们放入一个Shape类型的切片中。通过遍历这个切片,调用接口的Area方法,实现了代码复用,计算不同图形的面积。