You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
862 B
53 lines
862 B
3 years ago
|
package main
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"math"
|
||
|
)
|
||
|
|
||
|
// 接口
|
||
|
type jiheti interface {
|
||
|
area() float64
|
||
|
perim() float64
|
||
|
}
|
||
|
|
||
|
// 在react、circle上实现接口
|
||
|
type rect struct {
|
||
|
width, height float64
|
||
|
}
|
||
|
|
||
|
type circle struct {
|
||
|
radius float64
|
||
|
}
|
||
|
|
||
|
// 在Go中实现一个接口就要实现所有方法
|
||
|
// 在rect上实现Go的接口
|
||
|
func (r rect) area() float64 {
|
||
|
return r.width * r.height
|
||
|
}
|
||
|
func (r rect) perim() float64 {
|
||
|
return 2*r.width + 2*r.height
|
||
|
}
|
||
|
|
||
|
//在circle上实现接口
|
||
|
func (c circle) area() float64 {
|
||
|
return math.Pi*c.radius*c.radius
|
||
|
}
|
||
|
func (c circle) perim() float64 {
|
||
|
return 2*math.Pi*c.radius
|
||
|
}
|
||
|
|
||
|
// 调用接口中指定的方法,通过此便可以调用任何`jiheti`的接口了
|
||
|
func me(j jiheti){
|
||
|
fmt.Println(j)
|
||
|
fmt.Println(j.area())
|
||
|
fmt.Println(j.perim())
|
||
|
}
|
||
|
|
||
|
func main() {
|
||
|
r := rect{width: 3, height: 4}
|
||
|
c := circle{radius: 5}
|
||
|
me(r)
|
||
|
me(c)
|
||
|
}
|