其他分享
首页 > 其他分享> > Golang中的接口

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())
	}
}

标签:Area,sq,fmt,接口,Golang,type,side,float32
来源: https://www.cnblogs.com/tanbinghao/p/14755046.html