Go语言接口(interface)

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

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

接口底层采用结构体实现,其中iface对应非空接口,eface对应空接口。

iface
type itab struct {
	inter *interfacetype
	_type *_type
	link *itab
	hash unit32
	bad bool
	inhasn bool
	unused [2] byte
	fun [1] unintptr
}

type iface strcut {
	tab *itab
	data unsafe.Pointer
}
eface
type eface strcut {
	_type *_type
	data unsafe.Pointer
}

efaceiface相比,只维护了iface所有字段中的一个_type字段和data字段,表示空接口所承载的具体的实体类型,data是一个指针,指向具体的值。

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

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

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

// interface defintion
type interface_name interface {
	method_name1(parameter_list) [return_type1]
	method_name2(parameter_list) [return_type2]
	method_name3(parameter_list) [return_type3]
	...
	method_namen(parameter_list) [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
}

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

实例如下:

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)判断接口实际类型。

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")
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值