MST
星途 面试题库

面试题:Go接口与泛型编程 - 基础应用

在Go语言中,假设有一个接口`Shape`,包含方法`Area()`用于计算图形面积。请定义两个结构体`Circle`和`Rectangle`,实现`Shape`接口,并编写一个函数,该函数接受一个`Shape`类型的切片,计算并返回所有图形的总面积。另外,使用Go泛型实现一个简单的函数,用于交换切片中指定位置的两个元素。
33.8万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import (
    "fmt"
)

// 定义Shape接口
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 TotalArea(shapes []Shape) float64 {
    var total float64
    for _, shape := range shapes {
        total += shape.Area()
    }
    return total
}

// 使用Go泛型交换切片中指定位置两个元素的函数
func Swap[T any](slice []T, i, j int) {
    slice[i], slice[j] = slice[j], slice[i]
}

你可以使用以下方式调用这些函数:

func main() {
    circles := []Circle{
        {Radius: 2},
        {Radius: 3},
    }
    rectangles := []Rectangle{
        {Width: 4, Height: 5},
        {Width: 6, Height: 7},
    }

    var shapes []Shape
    for _, circle := range circles {
        shapes = append(shapes, circle)
    }
    for _, rectangle := range rectangles {
        shapes = append(shapes, rectangle)
    }

    total := TotalArea(shapes)
    fmt.Printf("所有图形的总面积: %f\n", total)

    numbers := []int{1, 2, 3, 4, 5}
    Swap(numbers, 1, 3)
    fmt.Println("交换后的切片:", numbers)
}