首页 > 其他 > 详细

Golang中的接口

时间:2021-05-11 17:14:21      阅读:22      评论:0      收藏:0      [点我收藏+]

定义接口

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

Golang中的接口

原文:https://www.cnblogs.com/tanbinghao/p/14755046.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!