Golang中的接口

定义接口

package main

import "fmt"

type Shaper interface {
	Area() float32
}
type Square struct {
	side float32
}

func (sq *Square) Area() float32  {
	return sq.side * sq.side
}

func main() {
	sq1 := new(Square)
	sq1.side = 5
	var areaIntf Shaper
	areaIntf = sq1
	fmt.Printf("The square has area: %f\n", areaIntf.Area())
}

定义接口-多态

package main

import "fmt"

type Shapers interface {
	Area() float32
}
type Squares struct {
	side float32
}

func (sq *Squares)Area()float32 {
	return sq.side * sq.side
}

type Rectangle struct {
	length, width float32
}

func (r Rectangle)Area()float32 {
	return r.length * r.width
}

func main() {
	r := Rectangle{5, 3}
	q := &Squares{5}
	shapes := []Shapers{r, q}
	for n, _ := range shapes {
		fmt.Println("Shape details: ", shapes[n])
		fmt.Println("Area of this shape is: ", shapes[n].Area())
	}
}
posted @ 2021-05-11 14:10  惊风破浪的博客  阅读(63)  评论(0编辑  收藏  举报