Golang教程:(十八)接口 - I
2017-07-17 08:10
423 查看
原文:https://golangbot.com/interfaces-part-1/
欢迎来到Golang系列教程的第十八篇。这个接口的第一部分,一共有两部分。
在 Go 中,一个接口定义为若干方法的签名。当一个类型定义了所有接口里的方法时,就说这个类型实现了这个接口。这和 OOP 很像。接口指定了一个类型应该包含什么方法,而该类型决定怎么实现这些方法。
比如
在 Playground 中运行
程序的第8行创建了一个接口类型名为
在下一行
在第15行我们添加了一个方法
在第28行,我们将
恭喜!你已经创建并实现了你的第一个接口。
现在让我们来看接口的一个实际用途。
我们将编写一个简单的程序,根据员工的个人工资计算公司的总支出。为了简洁起见,我们假设所有费用都是美元。
在 Playground 中运行
上面程序地第7行,定义了一个
在公司中我们有两种类型的员工:
第36行中,
最大的优点是可以将
程序的输出为:
让我们写一个程序来理解这一点。
在 Playground 中运行
在 Playground 中运行
上面程序的第7行,
在第13行,15行,21行,我们传递 string,int 和结构体给
i.(T)是用来获取接口
一个程序胜过千言万语:),让我们写一个类型断言。
在 Playground 中运行
第12行,
如果实际类型不是
在 Playground 中运行
在上面的程序中,我们将实际类型为
为了解决以上问题,我们可以使用下面的语法:
如果
如果
在 Playground 中运行
当
type switch 的语法与类型断言和很相似。在类型断言
在 Playground 中运行
上面的程序中,第8行,
在第20行,
也可以将类型和接口进行比较。如果我们有一个类型,并且该类型实现了一个接口,那么这个类型可以和它实现的接口进行比较。
让我们写一个程序来更清楚地了解这一点。
在 Playground 中运行
在上面的程序中,
程序的输出为:
接口第一部分的内容到这里就介绍完了。我们将在下一篇教程继续讨论接口的第二部分。感谢阅读。
目录
上一篇:Golang教程:(十七)方法
下一篇:Golang教程:(十九)接口 - II
欢迎来到Golang系列教程的第十八篇。这个接口的第一部分,一共有两部分。
什么是接口
在面向对象语言中,接口一般被定义为 :接口定义了一个对象的行为。它仅仅指定了一个对象应该做什么。具体怎么做(实现细节)是由对象决定的。在 Go 中,一个接口定义为若干方法的签名。当一个类型定义了所有接口里的方法时,就说这个类型实现了这个接口。这和 OOP 很像。接口指定了一个类型应该包含什么方法,而该类型决定怎么实现这些方法。
比如
WashingMachine可以作为一个接口,并提供两个函数
Cleaning()和
Drying()。任何提供了
Cleaning()和
Drying()方法定义的类型就可以说它实现了
WashingMachine接口。
声明和实现接口
让我们通过一个程序看一下如何声明和实现一个接口package main import ( "fmt" ) //interface definition type VowelsFinder interface { FindVowels() []rune } type MyString string //MyString implements VowelsFinder 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 Anderson") var v VowelsFinder v = name // possible since MyString implements VowelsFinder fmt.Printf("Vowels are %c", v.FindVowels()) }
在 Playground 中运行
程序的第8行创建了一个接口类型名为
VowelsFinder,它有一个方法
FindVowels() []rune。
在下一行
MyString类型被创建。
在第15行我们添加了一个方法
FindVowels() []rune给接受者类型
MyString。现在可以说
MyString实现了
VowelsFinder接口。这和其他语言大大的不同,比如在Java中,一个类必须用
implements关键字显式的标明实现了一个接口。这在Go中是不需要的,在Go中,如果一个类型包含了一个接口声明的所有方法,那么这个类型就隐式地实现了这个接口。
在第28行,我们将
MyString类型的变量
name赋值给
VowelsFinder类型的变量
v。这是合法的,因为
MyString实现了
VowelsFinder。在下一行,
v.FindVowels()在
MyString上调用
FindVowels方法打印在
Sam Anderson中所有的元音。程序的输出为:
Vowels are [a e o]。
恭喜!你已经创建并实现了你的第一个接口。
接口的实际用途
上面的程序告诉我们怎么创建和实现接口,但是没有展示接口的实际用途。在上面的程序中,我们可以使用name.FindVowels()替代
v.FindVowels(),程序照样可以工作,那么我们为什么还要使用接口呢?
现在让我们来看接口的一个实际用途。
我们将编写一个简单的程序,根据员工的个人工资计算公司的总支出。为了简洁起见,我们假设所有费用都是美元。
package main import ( "fmt" ) type SalaryCalculator interface { CalculateSalary() int } type Permanent struct { empId int basicpay int pf int } type Contract struct { empId int basicpay int } //salary of permanent employee is sum of basic pay and pf func (p Permanent) CalculateSalary() int { return p.basicpay + p.pf } //salary of contract employee is the basic pay alone func (c Contract) CalculateSalary() int { return c.basicpay } /* total expense is calculated by iterating though the SalaryCalculator slice and summing the salaries of the individual employees */ func totalExpense(s []SalaryCalculator) { expense := 0 for _, v := range s { expense = expense + v.CalculateSalary() } fmt.Printf("Total Expense Per Month $%d", expense) } func main() { pemp1 := Permanent{1, 5000, 20} pemp2 := Permanent{2, 6000, 30} cemp1 := Contract{3, 3000} employees := []SalaryCalculator{pemp1, pemp2, cemp1} totalExpense(employees) }
在 Playground 中运行
上面程序地第7行,定义了一个
SalaryCalculator接口类型,该接口只声明了一个方法:
CalculateSalary() int。
在公司中我们有两种类型的员工:
Permanent和
Contract(第 11 和 17 行)。永久性员工的工资是
basicpay和
pf的总和,而合同员工的工资只是基本工资
basicpay。这分别在第23行和第28行的方法
CalculateSalary中表示。通过声明这个方法,
Permanent和
Contract都实现了
SalaryCalculator接口。
第36行中,
totalExpense方法的声明展示了使用接口的好处。这个方法接收一个
SalaryCalculator接口的切片
[]SalaryCalculator作为参数。在第49行,我们将一个包含了
Permanent和
Contract类型的切片给方法
totalExpense。
totalExpense方法出通过调用各自类型的
CalculateSalary方法来计算总支。这是在第 39行完成的。
最大的优点是可以将
totalExpense扩展到任何新的员工类型,而不必修改任何代码。假设该公司引入了第三种员工类型
Freelancer和不同的计算工资的方法。那么
Freelancer可以被包含在传递给
totalExpense的切片参数中,而不需要修改任何
totalExpense方法的接口。这个方法会做自己应该做的事情,因为
Freelancer同样实现了
SalaryCalculator接口:)
程序的输出为:
Total Expense Per Month $14050。
接口的内部表示
可以把接口想象成这样一个元组(type, value)。
type是接口包含的具体类型,
value是接口包含的具体的值。
让我们写一个程序来理解这一点。
package main import ( "fmt" ) 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.7) t = f describe(t) t.Tester() }
在 Playground 中运行
Test接口提供了一个方法
Tester(),
MyFloat类型实现了这个接口。在第 24 行,我们将
MyFloat类型的变量
f赋值给
Test类型的变量
t。现在
t的具体类型是
MyFloat而它的值是
89.7。在第17行,
describe函数打印接口的值和具体类型。程序的输出为:
Interface type main.MyFloat value 89.7 89.7
空接口
一个没有声明任何方法的接口称为空接口。空接口表示为interface{}。因为空接口没有方法,因此所有类都都实现了空接口。
package main import ( "fmt" ) func describe(i interface{}) { fmt.Printf("Type = %T, value = %v\n", i, i) } func main() { s := "Hello World" describe(s) i := 55 describe(i) strt := struct { name string }{ name: "Naveen R", } describe(strt) }
在 Playground 中运行
上面程序的第7行,
describe(i interface{})函数接受一个空接口作为参数,因此任何值都可以传递给它。
在第13行,15行,21行,我们传递 string,int 和结构体给
describe。程序的输出结果为:
Type = string, value = Hello World Type = int, value = 55 Type = struct { name string }, value = {Naveen R}
类型断言
类型断言(type assertion)用来提取接口的实际类型的值。i.(T)是用来获取接口
i的实际类型
T的值的语法。
一个程序胜过千言万语:),让我们写一个类型断言。
package main import ( "fmt" ) func assert(i interface{}) { s := i.(int) //get the underlying int value from i fmt.Println(s) } func main() { var s interface{} = 56 assert(s) }
在 Playground 中运行
第12行,
s的实际类型是
int。在第8 行我们使用
i.(int)来获取
i的
int值。程序的输出为:
56。
如果实际类型不是
int,那么上面的程序会发生什么?让我们找出来:
package main import ( "fmt" ) func assert(i interface{}) { s := i.(int) fmt.Println(s) } func main() { var s interface{} = "Steven Paul" assert(s) }
在 Playground 中运行
在上面的程序中,我们将实际类型为
string的变量
s传递给
assert函数,
assert函数尝试从其中提取出一个
int值。该程序会触发 panic:
panic: interface conversion: interface {} is string, not int。
为了解决以上问题,我们可以使用下面的语法:
v, ok := i.(T)
如果
i的具体类型是
T,则
v将具有
i的实际值,
ok为
true。
如果
i的具体类型不是
T,则
ok将为
false,
v将具有
T的 0 值,程序不会触发 panic。
package main import ( "fmt" ) func assert(i interface{}) { v, ok := i.(int) fmt.Println(v, ok) } func main() { var s interface{} = 56 assert(s) var i interface{} = "Steven Paul" assert(i) }
在 Playground 中运行
当
Steven Paul传递给
assert函数,
ok将是
false因为
i的实际类型不是
int并且
v的值将是 0(
int的 0 值)。程序将输出:
56 true 0 false
Type Switch
类型分支(type switch)用来将一个接口的具体类型与多个 case 语句指定的类型进行比较。这很像普通的 switch 语句。唯一不同的是 type switch 中 case 指定的是类型,而普通的 switch 语句中 case 指定的是值。type switch 的语法与类型断言和很相似。在类型断言
i.(T)中,将类型
T替换为关键字
type就变成了 type switch。让我们通过下面的程序看看它是如何工作的。
package main import ( "fmt" ) func findType(i interface{}) { switch i.(type) { case string: fmt.Printf("I am a string and my value is %s\n", i.(string)) case int: fmt.Printf("I am an int and my value is %d\n", i.(int)) default: fmt.Printf("Unknown type\n") } } func main() { findType("Naveen") findType(77) findType(89.98) }
在 Playground 中运行
上面的程序中,第8行,
switch i.(type)是一个 type switch。每一个
case语句都将
i的实际类型和 case 指定的类型相比较。如果一个 case 匹配,则打印相应的语句。程序的输出为:
I am a string and my value is Naveen I am an int and my value is 77 Unknown type
在第20行,
89.98是
flaot64类型,并不匹配任何一个
case。因此在会后一行打印:
Unknown type。
也可以将类型和接口进行比较。如果我们有一个类型,并且该类型实现了一个接口,那么这个类型可以和它实现的接口进行比较。
让我们写一个程序来更清楚地了解这一点。
package main import "fmt" type Describer interface { Describe() } type Person struct { name string age int } func (p Person) Describe() { fmt.Printf("%s is %d years old", p.name, p.age) } func findType(i interface{}) { switch v := i.(type) { case Describer: v.Describe() default: fmt.Printf("unknown type\n") } } func main() { findType("Naveen") p := Person{ name: "Naveen R", age: 25, } findType(p) }
在 Playground 中运行
在上面的程序中,
Person结构体实现了
Describer接口。在第 19 行的 case 语句,
v和
Describe接口进行比较。由于
p实现了
Describer接口因此这个
case匹配成功,在第32行
findType(p)中
Person的
Describe()方法被调用。
程序的输出为:
unknown type Naveen R is 25 years old
接口第一部分的内容到这里就介绍完了。我们将在下一篇教程继续讨论接口的第二部分。感谢阅读。
目录
上一篇:Golang教程:(十七)方法
下一篇:Golang教程:(十九)接口 - II
相关文章推荐
- Golang教程:(十八)接口 - I
- Golang教程:(十九)接口 - II
- Golang初级系列教程-接口
- Golang初级系列教程-接口2
- Golang初级系列教程-接口多态性
- Golang教程:(十九)接口 - II
- 【HttpClient4.5中文教程】【第一章 :基础】1.2 HttpClient接口
- 燕十八公益教程-学习感想
- golang 接口
- thinkphp3.2支付宝接口类教程
- 基于C#的接口基础教程之二_C#教程
- PHP入门教程之面向对象的特性分析(继承,多态,接口,抽象类,抽象方法等)
- 基于C#的接口基础教程之四_C#教程
- 基于C#的接口基础教程之三_C#教程
- grpc(4):使用 golang 调用consul api 接口,注册user-tomcat服务
- 小波变换教程(十八)
- eoLinker-AMS接口管理系统 Mock API教程
- PHP类实例教程(二十三):PHP抽象类实现接口
- 【OpenCV入门教程之十八】OpenCV仿射变换 & SURF特征点描述合辑
- 利用golang语法检查对象是否实现了接口