Golang教程:(十八)接口 - I
原文:https://golangbot.com/interfaces-part-1/ 欢迎来到Golang系列教程的第十八篇。这个接口的第一部分,一共有两部分。 什么是接口在面向对象语言中,接口一般被定义为 :接口定义了一个对象的行为。它仅仅指定了一个对象应该做什么。具体怎么做(实现细节)是由对象决定的。 在 Go 中,一个接口定义为若干方法的签名。当一个类型定义了所有接口里的方法时,就说这个类型实现了这个接口。这和 OOP 很像。接口指定了一个类型应该包含什么方法,而该类型决定怎么实现这些方法。 比如 声明和实现接口让我们通过一个程序看一下如何声明和实现一个接口 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行创建了一个接口类型名为 在下一行 在第15行我们添加了一个方法 在第28行,我们将 恭喜!你已经创建并实现了你的第一个接口。 接口的实际用途上面的程序告诉我们怎么创建和实现接口,但是没有展示接口的实际用途。在上面的程序中,我们可以使用 现在让我们来看接口的一个实际用途。 我们将编写一个简单的程序,根据员工的个人工资计算公司的总支出。为了简洁起见,我们假设所有费用都是美元。 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行,定义了一个 在公司中我们有两种类型的员工: 第36行中, 最大的优点是可以将 程序的输出为: 接口的内部表示可以把接口想象成这样一个元组 让我们写一个程序来理解这一点。 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 %vn",t,t)
}
func main() {
var t Test
f := MyFloat(89.7)
t = f
describe(t)
t.Tester()
}
在 Playground 中运行
Interface type main.MyFloat value 89.7
89.7
空接口一个没有声明任何方法的接口称为空接口。空接口表示为 package main
import (
"fmt"
)
func describe(i interface{}) {
fmt.Printf("Type = %T,value = %vn",i,i)
}
func main() {
s := "Hello World"
describe(s)
i := 55
describe(i)
strt := struct {
name string
}{
name: "Naveen R",}
describe(strt)
}
在 Playground 中运行 上面程序的第7行, 在第13行,15行,21行,我们传递 string,int 和结构体给 Type = string,value = Hello World
Type = int,value = 55
Type = struct { name string },value = {Naveen R}
类型断言类型断言(type assertion)用来提取接口的实际类型的值。 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行, 如果实际类型不是 package main
import (
"fmt"
)
func assert(i interface{}) {
s := i.(int)
fmt.Println(s)
}
func main() {
var s interface{} = "Steven Paul"
assert(s)
}
在 Playground 中运行 在上面的程序中,我们将实际类型为 为了解决以上问题,我们可以使用下面的语法: v,ok := i.(T) 如果 如果 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 中运行 当 56 true
0 false
Type Switch类型分支(type switch)用来将一个接口的具体类型与多个 case 语句指定的类型进行比较。这很像普通的 switch 语句。唯一不同的是 type switch 中 case 指定的是类型,而普通的 switch 语句中 case 指定的是值。 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 %sn",i.(string))
case int:
fmt.Printf("I am an int and my value is %dn",i.(int))
default:
fmt.Printf("Unknown typen")
}
}
func main() {
findType("Naveen")
findType(77)
findType(89.98)
}
在 Playground 中运行 上面的程序中,第8行, I am a string and my value is Naveen
I am an int and my value is 77
Unknown type
在第20行, 也可以将类型和接口进行比较。如果我们有一个类型,并且该类型实现了一个接口,那么这个类型可以和它实现的接口进行比较。 让我们写一个程序来更清楚地了解这一点。 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 typen")
}
}
func main() {
findType("Naveen")
p := Person{
name: "Naveen R",age: 25,}
findType(p)
}
在 Playground 中运行 在上面的程序中, 程序的输出为: unknown type
Naveen R is 25 years old
接口第一部分的内容到这里就介绍完了。我们将在下一篇教程继续讨论接口的第二部分。感谢阅读。 目录 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |