Go 中接口的基本形式是一个命名的方法签名集合,其中没有任何具体实现。
1. 创建接口
如果你以前使用过面向对象语言,那么可能已经熟悉接口的概念。在 Go 中,可以使用 type 和 interface 关键字来定义接口类型。
type Name interface {
//methods
}
创建接口后,可以基于该接口创建变量。存储在这些变量中的值实现了接口的方法。
在其他编程语言(如 java )中,通常使用 implements 关键字来实现接口。在 Go 编程中,我们使用简单的约定,即接口类型的值只能保存实现接口方法的类型的值。要理解接口的概念,可参考下面代码:
package main
import "fmt"
type AccountOperations interface {
withdraw(value float64) bool
deposit(value float64) bool
displayInfo()
}
type account struct {
number string
balance float64
}
func (acct *account) withdraw(value float64) bool {
if acct.balance >= value {
acct.balance = acct.balance - value
return true
}
return false
}
func (acct *account) deposit(value float64) bool {
if value > 0 {
acct.balance = acct.balance + value
return true
}
return false
}
func (acct *account) displayInfo() {
fmt.Println("Account Balance:", acct.balance)
fmt.Println("Account Number:", acct.number)
}
func main() {
var ao AccountOperations
fmt.Println("initial value:", ao)
ao = &account{"C98664433332", 1500}
ao.withdraw(150)
ao.displayInfo()
ao.deposit(1000)
ao.displayInfo()
}
继续运行这个代码清单,应该能看到如下结果:
initial value: <nil>
Account Balance: 1350
Account Number: C98664433332
Account Balance: 2350
Account Number: C98664433332
下面让我们看看代码在做什么。
首先,创建一个名为 AccountOperations 的接口,它有 3 个方法签名:withdraw、deposit 和 displayInfo 。
接下来,创建一个结构体类型 account, 其中包含两个字段: number 和 balance 。这表示一个基本的银行帐