Files
go-basics/stage06-oop/01-interfaces/main.go
T

156 lines
2.6 KiB
Go
Raw Normal View History

2026-03-14 19:03:12 +08:00
package main
import (
"fmt"
"math"
)
type Shape interface {
Area() float64
Perimeter() float64
}
type Rectangle struct {
Width float64
Height float64
}
type Circle struct {
Radius float64
}
func (r Rectangle) Area() float64 {
return ____
}
func (r Rectangle) Perimeter() float64 {
return ____
}
func (c Circle) Area() float64 {
return math.Pi * ____ * ____
}
func (c Circle) Perimeter() float64 {
return 2 * math.Pi * ____
}
type ShapePrinter interface {
PrintInfo()
}
func (r Rectangle) PrintInfo() {
fmt.Printf("矩形 - 宽: %.2f, 高: %.2f\n", ____, ____)
}
func (c Circle) PrintInfo() {
fmt.Printf("圆形 - 半径: %.2f\n", ____)
}
func exercise1() float64 {
fmt.Println("=== 练习1:矩形接口实现 ===")
rect := Rectangle{Width: 10, Height: 5}
area := ____
perimeter := ____
fmt.Printf("矩形面积: %.2f, 周长: %.2f\n", area, perimeter)
return ____
}
func exercise2() string {
fmt.Println("=== 练习2:圆形接口实现 ===")
circle := Circle{Radius: 7}
area := ____
info := fmt.Sprintf("圆形面积: %.2f", area)
fmt.Println(____)
return ____
}
func exercise3() string {
fmt.Println("=== 练习3:多态 ===")
// 定义一个Shape类型的变量,分别指向Rectangle和Circle
var s Shape
s = ____
fmt.Printf("形状类型: %T, 面积: %.2f\n", s, s.____())
s = ____
fmt.Printf("形状类型: %T, 面积: %.2f\n", s, s.____())
return "多态演示完成"
}
func exercise4() interface{} {
fmt.Println("=== 练习4:空接口 ===")
// 空接口可以持有任何类型
var data interface{}
data = ____
fmt.Printf("数据: %v, 类型: %T\n", data, data)
data = ____
fmt.Printf("数据: %v, 类型: %T\n", data, data)
data = ____
fmt.Printf("数据: %v, 类型: %T\n", data, data)
return ____
}
type Animal interface {
Sound() string
}
type Dog struct{}
func (d Dog) Sound() string {
return "汪汪"
}
type Cat struct{}
func (c Cat) Sound() string {
return ____
}
func exercise5() string {
fmt.Println("=== 练习5:接口组合与使用 ===")
// 创建Animal切片,包含不同的动物
animals := []Animal{____, ____}
for _, animal := range ____ {
fmt.Printf("动物发出的声音: %s\n", animal.____())
}
return "动物接口演示完成"
}
func main() {
fmt.Println("=== 接口 练习 ===\n")
result1 := exercise1()
fmt.Printf("练习1结果: %.2f\n", result1)
result2 := exercise2()
fmt.Printf("练习2结果: %s\n", result2)
result3 := exercise3()
fmt.Printf("练习3结果: %s\n", result3)
result4 := exercise4()
fmt.Printf("练习4结果: %v (类型: %T)\n", result4, result4)
result5 := exercise5()
fmt.Printf("练习5结果: %s\n", result5)
}