Go 语言中的接口(Let‘s Go 二十五)

1、接口声明

Go并不像C#Java·等纯面向对象编程语言那样,它是没有这种面向对象的概念。

当然咯,Go中的接口是不能定义成员属性,只能有方法集(只有方法声明,没有方法实现体)。

type interfaceName interface {
    
    
    funcName(para paraType [,para2 paraType]) (returnType [,returnType])
    ...
}
package main

import (
	"fmt"
)

type article struct {
    
    
	artId   int
	title   string
	content string
}

type article interface {
    
    
	ShowArt() []article
	detilArt(artId int) article
}

func main() {
    
    

}

在这里插入图片描述

2、实现接口

Go中可没有像JavaC#中的implements这个关键字用来实现接口。

要想实现Go中的接口,类型实现接口方法集的方法,其类型实现的方法签名必须要与接口中的方法集中方法签名一样。

类型不需要显式声明它实现了某个接口:接口被隐式地实现。多个类型可以实现同一个接口。

实现某个接口的类型(除了实现接口方法外)可以有其他的方法。

一个类型可以实现多个接口。

接口类型可以包含一个实例的引用, 该实例的类型实现了此接口(接口是动态类型)。

package main

import (
	"fmt"
)

//定义一个 数学几何 接口
type shape interface {
    
    
	//用于计算 面积
	calArea() float64
}

type square struct {
    
    
	width float64
}

//通过 接受者 绑定 实现接口中的方法集
func (sq *square) calArea() float64 {
    
    
	return sq.width * sq.width
}

func main() {
    
    
    //实例化 square 结构类型
	sq := new(square)
	sq.width = 5
   //声明 shape 接口
    var sh shape
    sh = sq
	area := sh.calArea()
	fmt.Printf("边长为 %.0f 的面积是:%.2f \n", sq.width, area)
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/coco2d_x2014/article/details/127453291