Go语言之Interface(一)
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(一)的更多相关文章
- 浅析Go语言的Interface机制
前几日一朋友在学GO,问了我一些interface机制的问题.试着解释发现自己也不是太清楚,所以今天下午特意查了资料和阅读GO的源码(基于go1.4),整理出了此文.如果有错误的地方还望指正. GO语 ...
- Go语言之Interface(二)
使用指针接收器和值接收器实现接口 type Describer interface { Describe() } type Person struct { name string age int } ...
- Go语言入门——interface
1.Go如何定义interface Go通过type声明一个接口,形如 type geometry interface { area() float64 perim() float64 } 和声明一个 ...
- 浅解 go 语言的 interface(许的博客)
我写了一个 go interface 相关的代码转换为 C 代码的样例.也许有助于大家理解 go 的 interface.不过请注意一点,这里没有完整解析 go 语言 interface 的所有细节. ...
- Go语言第一深坑:interface 与 nil 的比较
interface简介 Go 语言以简单易上手而著称,它的语法非常简单,熟悉 C++,Java 的开发者只需要很短的时间就可以掌握 Go 语言的基本用法. interface 是 Go 语言里所提供的 ...
- Go语言的接口interface、struct和组合、继承
Go语言的interface概念相对于C++中的基类,通过interface来实现多态功能. 在C++中,当需要实现多态功能时,步骤是首先定义一个基类,该基类使用虚函数或者纯虚函数抽象了所有子类会用到 ...
- go 语言 interface{} 的易错点
一,interface 介绍 如果说 goroutine 和 channel 是 go 语言并发的两大基石,那 interface 就是 go 语言类型抽象的关键.在实际项目中,几乎所有的数据结构最底 ...
- 脚本语言:Xmas(二)
本篇,来谈谈类型系统,以及部分与垃圾收集器相关的内容. 一.基本类型 Xmas的基本类型:Null.Boolean.Label.String.Ref.Function.Integer.Float.De ...
- Go语言之三驾马车
作者:唐郑望,腾讯后台开发 工程师商业转载请联系腾讯WeTest获得授权,非商业转载请注明出处. WeTest 导读 Go语言的三个核心设计: interface | goroutine | cha ...
随机推荐
- mysql修改EST时区,mysql时间修改
方法有两种 ###第一种 select NOW();show variables like "%time_zone%"; ##一:通过sql命令临时修改 set global ti ...
- db2 SQL6036N解决办法
问题背景: 数据库在进行大量的运算和数据处理的过程中,IO.CPU等资源消耗非常高的时候,强制停止数据库.db2stop force 结果数据库命令迟迟没有响应.这个时候对数据库进行其他操作均无响应, ...
- java简单的文件读写工具类
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedRead ...
- redis、mysql、mongdb的比较
特点: 1-1 MySQL:1. 使用c和c++编写,并使用了多种编译器进行测试,保证源代码的可移植性2. 支持多种操作系统3. 为多种编程语言提供可API4. 支持多线程,充分利用CPU资源优化的S ...
- FortiGate日志中session clash
1.出现于:FortiGate v5.0和v5.2 2.出现原因 Session clash messages appear in the logs when a new session is cre ...
- 251. Flatten 2D Vector 平铺二维矩阵
[抄题]: Implement an iterator to flatten a 2d vector. Example: Input: 2d vector = [ [1,2], [3], [4,5,6 ...
- 244. Shortest Word Distance II 实现数组中的最短距离单词
[抄题]: Design a class which receives a list of words in the constructor, and implements a method that ...
- 【转载】我为什么弃用OpenStack转向VMware vsphere
我为什么弃用OpenStack转向VMware Vsphere,一切皆为简单.高效.因为我们在工作过程中涉及到大量的测试工作,每天都有成百个虚拟机的创建和销毁工作. 工作任务非常繁重,我们的持续集成平 ...
- Py西游攻关之RabbitMQ、Memcache、Redis
Py西游攻关之RabbitMQ.Memcache.Redis RabbitMQ 解释RabbitMQ,就不得不提到AMQP(Advanced Message Queuing Protocol)协议 ...
- 2019年Python数据挖掘就业前景前瞻
Python语言的崛起让大家对web.爬虫.数据分析.数据挖掘等十分感兴趣.数据挖掘就业前景怎么样?关于这个问题的回答,大家首先要知道什么是数据挖掘.所谓数据挖掘就是指从数据库的大量数据中揭示出隐含的 ...