golang的多态

定义了一个shape接口

type shape interface {
    area() float64 //计算面积
    perimeter() float64 //计算周长
}

需要注意的问题:如果想将一个结构体指针赋值给shape指针,则要求这个结构体必须实现所有已经在shape里定义好的函数

比如下面的代码,你把func (r *rect) area() float64改成func (r *rect) area2() float64就会报错。

package library

import "fmt"

type shape interface {
    area() float64 //计算面积
    perimeter() float64 //计算周长
}

type rect struct {
    width, height float64
}

func (r *rect) area() float64 { //面积
    return r.width * r.height
}

func (r *rect) perimeter() float64 {
    return 2 * (r.width + r.height)
}


type circle struct {
    radius float64
}

func (c *circle) area() float64 {
    return c.radius * c.radius * 3.14159
}

func (c *circle) perimeter() float64 {
    return 2 * c.radius * 3.14159
}

func InterfaceTest() {

    c := circle{radius: 3}
    r := rect {width:2, height:4}
    s := []shape{&r, &c}

    for _, v := range s {
        fmt.Printf("%v, %f, %f\n", v,  v.area(), v.perimeter())
    }

}

你可能感兴趣的:(golang的多态)