面试题答案
一键面试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)
}