面试题答案
一键面试package main
import (
"fmt"
"math"
)
// Shape接口定义
type Shape interface {
Area() float64
}
// Circle结构体
type Circle struct {
Radius float64
}
// Circle实现Shape接口的Area方法
func (c Circle) Area() float64 {
return math.Pi * 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
}
// 接受Shape接口类型参数并调用Area方法打印结果的函数
func printArea(s Shape) {
fmt.Printf("Area is: %f\n", s.Area())
}
你可以使用以下方式调用这些函数和结构体:
func main() {
circle := Circle{Radius: 5}
rectangle := Rectangle{Width: 4, Height: 6}
printArea(circle)
printArea(rectangle)
}