Go 语言提供了另外一种数据类型即接口,它把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口
// 定义接口
type interface_name interface {
method_name1 [return_type]
method_name2 [return_type]
method_name3 [return_type]
...
method_namen [return_type]
}
// 实现接口方法
func (struct_name_variable struct_name) method_name1() [return_type] {
// 方法实现
}
// 定义结构体
type struct_name struct {
// variables
}
func (struct_name_variable struct_name) method_namen() [return_type] {
// 方法实
}
package main
import (
"fmt"
)
type Phone interface {
call() string
say()
}
type NokiaPhone struct {
name string
}
func (nokiaPhone NokiaPhone) say() {
fmt.Println("Hello, I am Nokia")
}
func (nokiaPhone NokiaPhone) call() string {
return "I am Nokia, I can call you!"
}
type IPhone struct {
name string
}
func (iPhone IPhone) say(){
fmt.Println("Hello, I am iPhone")
}
func (iPhone IPhone) call() string{
return "I am iPhone, I can call you!"
}
func main() {
var nokiaPhone NokiaPhone
nokiaPhone = NokiaPhone{name:"nokiaPhone"}
fmt.Println(nokiaPhone.name)
nokiaPhone.call()
nokiaPhone.say()
i := IPhone{name:"张三"}
var iphone Phone = i
// iphone = new(IPhone)
// iphone = &IPhone{name:"张三"} //注意iphone = new(IPhone)也可以写作前面这样的
fmt.Println(i.name)
iphone.call()
iphone.say()
i.say()
}
/*
在上面的例子中,我们定义了一个接口Phone,接口里面有一个方法call()。
然后我们在main函数里面定义了一个Phone类型变量,
并分别为之赋值为NokiaPhone和IPhone。然后调用call()方法,输出结果如下:
I am Nokia, I can call you!
I am iPhone, I can call you!
*/
package main
import "fmt"
// Interface Men被Human,Student和Employee实现
// 因为这三个类型都实现了这两个方法
type Men interface {
SayHi()
Sing(lyrics string)
}
type Human struct {
name string
age int
phone string
}
type Student struct {
Human //匿名字段
school string
loan float32
}
type Employee struct {
Human //匿名字段
company string
money float32
}
//Human实现SayHi方法
func (h Human) SayHi() {
fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
}
//Human实现Sing方法
func (h Human) Sing(lyrics string) {
fmt.Println("La la la la...", lyrics)
}
//Employee重载Human的SayHi方法
func (e Employee) SayHi() {
fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
e.company, e.phone)
}
func main() {
mike := Student{Human{"Mike", 25, "222-222-XXX"}, "MIT", 0.00}
paul := Student{Human{"Paul", 26, "111-222-XXX"}, "Harvard", 100}
sam := Employee{Human{"Sam", 36, "444-222-XXX"}, "Golang Inc.", 1000}
Tom := Employee{Human{"Tom", 37, "222-444-XXX"}, "Things Ltd.", 5000}
//定义Men类型的变量i
var i Men
//i能存储Student
i = mike
fmt.Println("This is Mike, a Student:")
i.SayHi()
i.Sing("November rain")
//i也能存储Employee
i = Tom
fmt.Println("This is Tom, an Employee:")
i.SayHi()
i.Sing("Born to be wild")
//定义了slice Men
fmt.Println("Let's use a slice of Men and see what happens")
x := make([]Men, 3)
//这三个都是不同类型的元素,但是他们实现了interface同一个接口
x[0], x[1], x[2] = paul, sam, mike
for _, value := range x{
value.SayHi()
}
}