Go语言之Interface(一)

什么是interface

在面向对象语言中接口是:接口定义了一个对象的行为,但在Go中接口就是方法签名的集合,当一个类型提供了这个接口中的所有的方法,就可以说这个类型实现了这个接口

接口的声明和实现
package main

import (
"fmt"
) // 接口的声明
type VowelsFinder interface {
FindVowels() []rune
} type MyString string // 接口的实现
func (ms MyString) FindVowels() []rune {
var vowels []rune
for _, rune := range ms {
if rune == 'a' || rune == 'e' || rune == 'i' || rune == 'o' || rune == 'u' {
vowels = append(vowels, rune)
}
}
return vowels
} func main() {
name := MyString("Sam Andreson")
var v VowelsFinder
v = name
fmt.Printf("Vowels are %c", v.FindVowels())
}
声明一个接口
// 接口的声明
type VowelsFinder interface {
FindVowels() []rune
}
实现接口
type MyString string

// 接口的实现
func (ms MyString) FindVowels() []rune {
var vowels []rune
for _, rune := range ms {
if rune == 'a' || rune == 'e' || rune == 'i' || rune == 'o' || rune == 'u' {
vowels = append(vowels, rune)
}
}
return vowels
}
练习使用接口
type SalaryCalculator interface {
CalculateSalary() int
} type Permanent struct {
empId int
basicpay int
pf int
} type Contract struct {
empId int
basicpay int
} func (p Permanent) CalculateSalary() int {
return p.basicpay + p.pf
} func (c Contract) CalculateSalary() int {
return c.basicpay
} func totalExpense(s []SalaryCalculator) {
expense := 0
for _, v := range s {
expense = expense + v.CalculateSalary()
}
fmt.Printf("Totla Expense per Month $%d", expense)
} func main() {
pemp1 := Permanent{1, 5000, 20}
pemp2 := Permanent{2, 5000, 30}
cemp1 := Contract{3, 3000} employes := []SalaryCalculator{pemp1, pemp2, cemp1}
totalExpense(employes)
}
接口的内部表示

接口内部可以看着是一个元组 (type,value),type表示接口的具体类型,value表示这个具体类型的值

type Test interface {
Tester()
} type MyFloat float64 func (m MyFloat) Tester() {
fmt.Println(m)
} func describe(t Test) {
fmt.Printf("Interface type %T value %v\n", t, t)
} func main() {
var t Test
f := MyFloat(89.4)
t = f
describe(t)
t.Tester()
}

输出结果

Interface type main.MyFloat value 89.4
89.4
空接口

如果一个接口没有包含方法,那么这个接口就是一个空接口 interface{},由于空接口中没有方法,所以所有的类型都可以实现空接口

func descrip(i interface{}) {
fmt.Printf("Type = %T,value = %v\n", i, i)
} func main() {
s := "Hello,World"
descrip(s)
i := 55
descrip(i) strt := struct {
name string
}{
name: "CoderMiner",
}
descrip(strt)
}

输出结果是

Type = string,value = Hello,World
Type = int,value = 55
Type = struct { name string },value = {CoderMiner}
类型断言(类型转换)

类型转换的语法 i.(T),把i转换为类型T

如转换为int类型

func asstert(i interface{}) {
s := i.(int)
fmt.Println(s)
} var s1 interface{} = 56
asstert(s1)

但如果在类型转换时,如果是不同类型转换会发生什么呢?

string转换为int

func asstert(i interface{}) {
s := i.(int)
fmt.Println(s)
}
var s1 interface{} = "hello"
asstert(s1)

输出结果是

panic: interface conversion: interface {} is string, not int

会触发panic,类型转换失败,如果要避免出现panic,可以使用下面的方法

v, ok := i.(T)

如果能够转换成功,ok的值是true,转换失败就是false

func asstert(i interface{}) {
s, ok := i.(int)
fmt.Println(s, ok)
}
var s1 interface{} = "hello"
asstert(s1)
var s2 interface{} = 56
asstert(s2)

输出结果

0 false
56 true
类型判断

语法是

i.(type)
func FindType(i interface{}) {
switch i.(type) {
case string:
fmt.Printf("this is the string type and the value is %s\n", i.(string))
case int:
fmt.Printf("this is the int type and the value is %d\n", i.(int))
default:
fmt.Printf("Unknown type\n")
}
} FindType("CoderMiner")
FindType(77)
FindType(69.3)

Go语言之Interface(一)的更多相关文章

  1. 浅析Go语言的Interface机制

    前几日一朋友在学GO,问了我一些interface机制的问题.试着解释发现自己也不是太清楚,所以今天下午特意查了资料和阅读GO的源码(基于go1.4),整理出了此文.如果有错误的地方还望指正. GO语 ...

  2. Go语言之Interface(二)

    使用指针接收器和值接收器实现接口 type Describer interface { Describe() } type Person struct { name string age int } ...

  3. Go语言入门——interface

    1.Go如何定义interface Go通过type声明一个接口,形如 type geometry interface { area() float64 perim() float64 } 和声明一个 ...

  4. 浅解 go 语言的 interface(许的博客)

    我写了一个 go interface 相关的代码转换为 C 代码的样例.也许有助于大家理解 go 的 interface.不过请注意一点,这里没有完整解析 go 语言 interface 的所有细节. ...

  5. Go语言第一深坑:interface 与 nil 的比较

    interface简介 Go 语言以简单易上手而著称,它的语法非常简单,熟悉 C++,Java 的开发者只需要很短的时间就可以掌握 Go 语言的基本用法. interface 是 Go 语言里所提供的 ...

  6. Go语言的接口interface、struct和组合、继承

    Go语言的interface概念相对于C++中的基类,通过interface来实现多态功能. 在C++中,当需要实现多态功能时,步骤是首先定义一个基类,该基类使用虚函数或者纯虚函数抽象了所有子类会用到 ...

  7. go 语言 interface{} 的易错点

    一,interface 介绍 如果说 goroutine 和 channel 是 go 语言并发的两大基石,那 interface 就是 go 语言类型抽象的关键.在实际项目中,几乎所有的数据结构最底 ...

  8. 脚本语言:Xmas(二)

    本篇,来谈谈类型系统,以及部分与垃圾收集器相关的内容. 一.基本类型 Xmas的基本类型:Null.Boolean.Label.String.Ref.Function.Integer.Float.De ...

  9. Go语言之三驾马车

    作者:唐郑望,腾讯后台开发 工程师商业转载请联系腾讯WeTest获得授权,非商业转载请注明出处.  WeTest 导读 Go语言的三个核心设计: interface | goroutine | cha ...

随机推荐

  1. 2018年秋季学期面向对象程序设计(JAVA)课程总结

    2018年秋季学期面向对象程序设计(JAVA)课程总结 时值2018年年末,按惯例对本学期教学工作小结如下: 1. 教学资源与教学辅助平台 教材:凯 S.霍斯特曼 (Cay S. Horstmann) ...

  2. Django 学生信息 添加 功能 遇到的问题.

    1  添加 班级信息时的问题 (grade为外键) 原因是 grade 必需接收 一个 实例, 而我交是一个 str字符串, if request.method == 'POST': data = { ...

  3. C++ 实现 split 操作

    理由:由于 C++ 标准库里面没有字符分割函数 split ,这可太不方便了,我们利用 STL 来实现自己的 split 函数: 原型:vector<string> split(const ...

  4. 289. Game of Life数组生存游戏

    [抄题]: According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a ...

  5. 关于java中分割字符串

    例子:String path = "123.456.789"; 如果要使用“.”将path分割成String[], path.split("//."); or ...

  6. 交叉编译sudo

    编译Sudo version 1.8.6p7下载路径:https://www.sudo.ws/news.html 1.交叉编译 # tar -xvf sudo-1.8.6p7.tar.gz # cd ...

  7. Quartz.Net进阶之二:关于触发器的更多信息

    与作业一样,触发器相对容易使用,但是在您可以充分利用Quartz.NET之前,确实需要了解和理解各种可自定义的选项. 此外,如前所述,您可以选择不同类型的触发器来满足不同的调度需求. 1.常见触发器属 ...

  8. 对于PHP面试知识点的小结

    基础篇 了解大部分数组处理函数 字符串处理函数(区别 mb_ 系列函数) & 引用,结合案例分析 == 与 === 区别 isset 与 empty 区别 全部魔术函数理解 static.$t ...

  9. 结合OPENSIFT源码详解SIFT算法

    平台:win10 x64 +VS 2015专业版 +opencv-2.4.11 + gtk_-bundle_2.24.10_win32 参考博客:https://www.cnblogs.com/cql ...

  10. SAS数据集

    SAS数据集是存储在SAS逻辑库中.由SAS创建和处理的SAS文件,是SAS存储数据的主要方式.SAS数据集包含以表的观测(行)和 变量(列)为形式存在的数据值,以及用以描述变量类型.长度和创建该数据 ...