文章转载地址:https://www.flysnow.org/2017/04/03/go-in-action-go-interface.html

1.什么是 interface?

简单的说,interface 是一组 method 签名的组合,通过 interface 定义对象的一组行为

上一篇文章中我们实现了 Student 和 Employee 都能 SayHi,现在我们进一步做扩展,Student 和 Employee

实现另一个方法 Sing,然后 Student 实现方法 BorrowMoney 而 Employee 实现 SpendSalary

这样,Student 实现了三个方法:SayHi,Sing,BorrowMoney ;而 Employee 实现了 SayHi,Sing, SpendSalary

上面这些方法的组合被称为 interface(被对象 Student 和 Employee 实现)。例如:Student 和 Employee 都实现了 interface:

SayHi,Sing,也就是这两个对象是该 interface 类型。而 Employee 没有实现这个 interface:SayHi,Sing,BorrowMoney,

是因为 Employee 没有实现 BorrowMoney 这个方法

2. interface 类型

  interface 定义了一组方法,如果某个对象实现了某个接口的所有方法,则此对象就实现了这个接口

package main

import "fmt"

// 定义 Human 结构体
type Human struct {
name string
age int
phone string
} // 定义 Student 结构体
type Student struct {
Human // 匿名字段
company string
loan float32
} // 定义结构体 Employee
type Employee struct {
Human // 匿名字段
company string
money float32
} // Human 实现 SayHi 方法
func (h *Human) SayHi() {
fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
} // Human 实现 Sing 方法 传入 lyrics(歌词) 参数
func (h *Human) Sing(lyrics string) {
fmt.Println("La la, la la la, la la la la la...", lyrics)
} // Human 实现 Guzzle 方法
func (h *Human) Guzzle(beerStein string) {
fmt.Println("Guzzle Guzzle Guzzle...", beerStein)
} // Employee 重载 Human 的 SayHi 方法
func (e *Employee) SayHi() {
fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
e.company, e.phone)
} // Student 实现 BorrowMoney 方法
func (s *Student) BorrowMoney(amount float32) {
s.loan += amount
} // Employee 实现 SpendSalary 方法
func (e *Employee) SpendSalary(amount float32) {
e.money -= amount
} // 定义 interface
type Men interface {
SayHi()
Sing(lyrics string)
Guzzle(beerStein string)
} type YoungChap interface {
SayHi()
Sing(lyrics string)
BorrowMoney(amount float32)
} type ElderlyGent interface {
SayHi()
Sing(lyrics string)
SpendSalary(amount float32)
} func main() { }

  通过上面的代码我们可以知道,interface 可以被任意的对象实现。我们看到上面的 Men interface 被 Human、Student、Employee

实现(一个接口可以被多个对象实现)。同理,一个对象可以实现任意多个接口,例如上面的 Student 实现了 Men 和 YoungChap 两个interface

最后,任意的类型都实现了空接口(interface{})

3. interface 值

    

package main

import "fmt"

// 定义 Human 结构体
type Human struct {
name string
age int
phone string
} // 定义 Student 结构体
type Student struct {
Human // 匿名字段
company string
loan float32
} // 定义结构体 Employee
type Employee struct {
Human // 匿名字段
company string
money float32
} // Human 实现 SayHi 方法
func (h Human) SayHi() {
fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
} // Human 实现 Sing 方法 传入 lyrics(歌词) 参数
func (h Human) Sing(lyrics string) {
fmt.Println("La la, la la la, la la la la la...", lyrics)
} // Employee 重载 Human 的 SayHi 方法
func (e Employee) SayHi() {
fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
e.company, e.phone)
} // Interface Men 都被 Human、Student、Employee 实现
type Men interface {
SayHi()
Sing(lyrics string)
} func main() {
mike := Student{Human{"Mike",25,"222-222-xxx"},"MIT",0.00}
paul := Student{Human{"Paul",26,"111-222-xxx"},"Harvard",100} sam := Employee{Human{"Sam",36,"444-222-xxx"},"Golang Inc.",1000}
tom := Employee{Human{"Tom",37,"222-444-xxx"},"Things Ltd.",5000} // 定义 Men 类型的 i
var i Men // i 能存储 Student
i = mike
fmt.Println("This is Mike,a Student:")
i.SayHi()
i.Sing("November rain") // i 也能存储 Employee
i = tom
fmt.Println("This is tom, an Employee:")
i.SayHi()
i.Sing("Born to be wild") // 定义slice Men
fmt.Println("Let's use a slice of Men and see what happens")
x := make([]Men,3) // 这三个都是不同类型的元素,但是他们实现了interface同一个接口
x[0],x[1],x[2] = paul,sam,mike for _,value := range x{
value.SayHi()
}
} -------------------------------------------------------------------------- 输出结果: This is Mike,a Student:
Hi, I am Mike you can call me on 222-222-xxx
La la, la la la, la la la la la... November rain
This is tom, an Employee:
Hi, I am Tom, I work at Things Ltd.. Call me on 222-444-xxx
La la, la la la, la la la la la... Born to be wild
Let's use a slice of Men and see what happens
Hi, I am Paul you can call me on 111-222-xxx
Hi, I am Sam, I work at Golang Inc.. Call me on 444-222-xxx
Hi, I am Mike you can call me on 222-222-xxx

4.空 interface 

  空 interface(interface{}) 不包含任何的 method,正因为如此,所有类型都实现了空 interface。空 interface 对于描述

起不到任何作用(因为它不包含任何的 method),但是空 interface 在我们需要存储任意类型的数值的时候相当有用,因

为它可以存储任意类型的数值。如下示例:

// 定义 a 为空接口
var a interface{}
var i int = 5 s := "Hello world' // a 可以存储任意类型的数值
a = i
a = s

 一个函数把 interface{} 作为参数,则可以接受任意类型的值作为参数,如果一个函数返回 interface{} ,那么也就可以

返回任意类型的值

5.interface 变量存储的类型

  我们知道  interface 的变量里面可以存储任意类型的数值(该类型实现了 interface),那么我们如何反向知道这个变量里面实际保存

的是哪个类型的对象?目前有两种方式:

5.1 Comma-ok 断言

Go 语言里面有一个语法,可以直接判断是否是该类型的变量:value,ok = element.(T),这里 value 就是变量的值,ok 是一个

bool 类型,element 是 interface 变量,T 是断言的类型

如果 element 里面确实存储了 T 类型的数值,那么 ok 返回 true,否则返回 false

如下示例:

package main

import (
"fmt"
"strconv"
) // 定义一个空接口
type Eelement interface {} type List [] Eelement // 定义一个 Person 结构体
type Person struct {
name string
age int
} // 给 Person 绑定一个方法
func (p Person) String() string{
return "(name: " + p.name + " - age: "+strconv.Itoa(p.age)+ " years)"
} func main() {
list := make(List,3)
list[0] = 1 // an int
list[1] = "Hello" // a string
list[2] = Person{"Dennis",70} for index,element := range list{
// 类型判断
if value,ok := element.(int);ok{
fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
}else if value,ok := element.(string);ok{
fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
}else if value,ok := element.(Person);ok{
fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
}else{
fmt.Printf("list[%d] is of a different type\n", index)
}
}
}
---------------------------------------------------------------------------------- 输出结果: list[0] is an int and its value is 1
list[1] is a string and its value is Hello
list[2] is a Person and its value is (name: Dennis - age: 70 years)

  5.2 type-switch

直接看示例:

package main

import (
"fmt"
"strconv"
) // 定义一个空接口
type Eelement interface {} type List [] Eelement // 定义一个 Person 结构体
type Person struct {
name string
age int
} // 给 Person 绑定一个方法
func (p Person) String() string{
return "(name: " + p.name + " - age: "+strconv.Itoa(p.age)+ " years)"
} func main() {
list := make(List,3)
list[0] = 1 // an int
list[1] = "Hello" // a string
list[2] = Person{"Dennis",70} for index,element := range list{
// 使用 type-switch 做类型判断
switch value := element.(type) {
case int:
fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
case string:
fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
case Person:
fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
default:
fmt.Println("list[%d] is of a different type", index)
}
}
} ------------------------------------------------------------------------------------- 输出结果: list[0] is an int and its value is 1
list[1] is a string and its value is Hello
list[2] is a Person and its value is (name: Dennis - age: 70 years)

6. 嵌入 interface

    如果一个 interface1 作为 interface2 的一个嵌入字段,那么 interface2 隐式的包含了 interface1 里面的method

在源码包 container/heap 里面有这样的一个定义:

type Interface interface {
sort.Interface
Push(x interface{}) // add x as element Len()
Pop() interface{} // remove and return element Len() - 1.
}

 看如上代码片段,我们看到 sort.Interface 其实就是嵌入字段,把 sort.Interface 的所有 method 给隐式的包含进来了,

即下面的方法:

type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}

  另外一个就是 io 包下面的 io.ReadWriter ,它包含了 io 包下面的两个 interface:Reader、Writer

// ReadWriter is the interface that groups the basic Read and Write methods.
type ReadWriter interface {
Reader
Writer
}

 下面再来看一个示例:

package main

import "fmt"

// 定义一个 USB interface
type USB interface {
Name() string
// interface 嵌入
Connecter
} // 定义一个 Connecter interface
type Connecter interface {
Connect()
} // 定义一个 struct
type PhoneConnecter struct {
name string
} // 给 PhoneConnecter 绑定 Name 方法
func (pc PhoneConnecter) Name() string{
return pc.name
} // 绑定 Connect 方法
func (pc PhoneConnecter) Connect() {
fmt.Println("Connected:",pc.name)
} func main() {
a := PhoneConnecter{"PhoneConnecter"}
a.Name()
a.Connect()
}

  

Go 接口(interface)的更多相关文章

  1. java中的接口interface

    关于接口 接口描述了实现了它的类拥有什么功能.因为Java是强类型的,所以有些操作必须用接口去约束和标记.接口作为类的能力的证明,它表明了实现了接口的类能做什么. 类似与class,interface ...

  2. php中的抽象类(abstract class)和接口(interface)

    一. 抽象类abstract class 1 .抽象类是指在 class 前加了 abstract 关键字且存在抽象方法(在类方法 function 关键字前加了 abstract 关键字)的类. 2 ...

  3. 14 接口-interface的定义与实现

    接口的基本语法一: 1.使用interface 定义 2.接口当中的方法都是抽象方法 3.接口当中的方法都是public权限 接口的定义: interface USB { public void re ...

  4. C#编程利器之三:接口(Interface)【转】

    C#编程利器之三:接口(Interface) C#接口是一个让很多初学者容易迷糊的东西,用起来好象很简单,定义接口,然后在里面定义方法,通过继承与他的子类来完成具体的实现.但没有真正认识接口的作用的时 ...

  5. 为什么不能把委托(delegate)放在一个接口(interface)当中?

    stackoverflow上有人问,为什么不能把委托放在一个接口当中? 投票最多的第一个答案第一句话说,“A Delegate is just another type, so you don't g ...

  6. java之接口interface

    接口 1.多个无关的类可以实现同一个接口 2.一个类可以实现多个无关的接口 3.与继承关系类似,接口与实现类之间存在多态性 4.定义java类的语法格式 < modifier> class ...

  7. 【Java 基础篇】【第六课】接口interface

    Java提供的这个interface的语法,目的就是将接口从类中剥离出来,构成独立的主体. 首先加入我们定义了这个杯子接口: interface Cup { void addWater(int w); ...

  8. TypeScript学习指南第二章--接口(Interface)

    接口(Interface) TypeScript的核心机制之一在于它的类型检查系统(type-checker)只关注一个变量的"模型(shape)" 稍后我们去了解这个所谓的形状是 ...

  9. Go语言学习笔记(四)结构体struct & 接口Interface & 反射

    加 Golang学习 QQ群共同学习进步成家立业工作 ^-^ 群号:96933959 结构体struct struct 用来自定义复杂数据结构,可以包含多个字段(属性),可以嵌套: go中的struc ...

  10. Java接口interface

    Java接口interface 1.多个无关的类可以实现同一个接口. 2.一个类可以实现多个无关的接口. 3.与继承关系类似,接口与实现类之间存在多态性. 接口(interface)是抽象方法和常量值 ...

随机推荐

  1. C# word 图片大小

    通过Office自带的类库word文档中插入图片,图片大小的单位为磅 而文档中,图片的大小已经固定,为CM. 实际工作中,首先将图片插入到word中,根据目前的大小,计算转换为目标大小的比率,将长宽按 ...

  2. SetTimer API函数

    位于user32.dll中,可以每隔一段时间执行一段时间执行一件事的时候,可以使用它. 使用定时器,通常告诉Windows一个时间间隔,然后Windows以此时间间隔周期性触发程序. 发送WM_TIM ...

  3. Spring-Boot数据库密码加密配置

    springboot集成mysql/oracle时需要在yml/properties中配置数据库信息,用户名密码是肯定有的,所以就涉及到密码的加密,当然不加密也是可以的,正如某位大佬所说的,不加密就像 ...

  4. c3p0 空指针异常 com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.

    com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@11d9f05 -- Acquisition Attempt Failed!!! C ...

  5. ArcPy中mapping常见函数及用法1

    arcpy的mapping模块常见属性方法总结1.如何获取当前地图文档: 方式:mxd = mapping.MapDocument("CURRTENT")引用本地或者网络文档(ar ...

  6. POJ 3126 - Prime Path - [线性筛+BFS]

    题目链接:http://poj.org/problem?id=3126 题意: 给定两个四位素数 $a,b$,要求把 $a$ 变换到 $b$.变换的过程每次只能改动一个数,要保证每次变换出来的数都是一 ...

  7. MySQL数据库基础备份

    1.备份命令 格式:mysqldump -h主机名 -P端口 -u用户名 -p密码 --database 数据库名 > 文件名.sql mysqldump -h -uroot -ppasswor ...

  8. 使用APScheduler启动Django服务时自动运行脚本(可设置定时运行)

    Django搭建的服务器一般都用作WEB网站进行访问,通常的形式是用户访问网站或点击按钮发送请求,Django检测到请求后进行相应的试图函数处理后返回页面给用户. 但是,我们有时会需要有一些后台自动运 ...

  9. Python---http协议.md

    一.什么是URL? URL即统一资源定位符(Uniform Resource Locator),用来唯一地标识万维网中的某一个文档.URL由协议.主机和端口(默认为80)以及文件名三部分构成,如: h ...

  10. React之ant design的table表格序号连续自增

    render(text,record,index){     return(       <span>{(pagination.current-1)*10+index+1}</spa ...