前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Go语言接口

Go语言接口

作者头像
Steve Wang
发布2020-12-23 15:13:33
3420
发布2020-12-23 15:13:33
举报
文章被收录于专栏:从流域到海域

Go语言中的接口不是Java面向对象的那个接口,而是一种数据类型。但Go的接口多多少少继承了面向对象的那个接口的概念。笔者认为接口、结构体以及实现接口的方法三者组合起来,就能够实现面向对象。

Go语言定义了新的数据类型接口(Interface)。Go语言的接口会将所有具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了该接口。

Go语言中的接口类型有如下特性:

  • 包含0个或者多个方法的签名
  • 只定义方法的签名,不包含实现
  • 实现接口不需要显式的声明,需要实现接口中的所有方法

接口定义使用interface关键字,语法如下:

代码语言:javascript
复制
// interface defintion
type interface_name interface {
	method_name1 [return_type1]
	method_name2 [return_type2]
	method_name3 [return_type3]
	...
	method_namen [return_typen]
}
// struct defintion
type struct_name struct {
	
}

// implement interface
func (struct_name_variable1 struct_name) method_name1() [return_type1] {
	//method implementation
}

func (struct_name_variable2 struct_name) method_name2) [return_type2] {
	//method implementation
}

该例说明,普通的方法定义用于实现接口的方法的定义不一样的

实例如下:

代码语言:javascript
复制
package main

import "fmt"

type Phone interface {
	call() int
}

type ApplePhone struct {
	phoneType string
}

type SumsungPhone struct {
	phoneType string
}

func (iphone ApplePhone) call() int {
	fmt.Println("This is a call from", iphone.phoneType)
	return 1
}

func (sphone SumsungPhone) call() int {
	fmt.Println("This is a call from", sphone.phoneType)
	return 2
}

func main() {
	iphone := ApplePhone{"iphone"}
	sphone := SumsungPhone{"Sumsung"}

	fmt.Println(iphone.call())
	fmt.Println(sphone.call())
}

// This is a call from iphone
// 1
// This is a call from Sumsung
// 2

在该例中,只有方法显式声明了它实现的是接口中的哪一个方法,其余都没有显式声明,但却实现了接口、结构体、方法三者的动态绑定。Go语言内置了这种绑定的实现。interface实现的底层原理留坑待填。

判断接口实际类型

可以使用interface.(type)判断接口实际类型。

代码语言:javascript
复制
package main

import (
	"fmt"
)

type Phone interface {
	call() int
}

type ApplePhone struct {
	phoneType string
}

type SumsungPhone struct {
	phoneType string
}

func (iphone ApplePhone) call() int {
	fmt.Println("This is a call from", iphone.phoneType)
	return 1
}

func (sphone SumsungPhone) call() int {
	fmt.Println("This is a call from", sphone.phoneType)
	return 2
}

func main() {
	var phone Phone =  ApplePhone{"iphone"}
	switch phone.(type) {
	case ApplePhone:
		fmt.Println("This is a ApplePhone")
	case SumsungPhone:
		fmt.Println("This is a SumSungPhone")
	default:
		fmt.Println("No match item")
	}
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/12/21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 判断接口实际类型
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档