package main
import "fmt"
type IReader interface {
Read(buf []byte) (n int, err error)
}
type IWriter interface {
Write(buf []byte) (n int, err error)
}
type ICloser interface {
Close() error
}
type File struct {
name string
}
func (file *File) Write(buf []byte) (n int, err error) {
fmt.Println("Write")
return 0, nil
}
func (file *File) Read(buf []byte) (n int, err error) {
fmt.Println("Read")
return 0, nil
}
func (file *File) Close() error {
fmt.Println("Close")
return nil
}
type A interface {
A()
B()
}
type AReal struct {}
func (*AReal) A() {}
func (*AReal) B() {}
type B interface {
A()
B()
}
type BReal struct {}
func (*BReal) A() {}
func (*BReal) B() {}
type C interface {
A()
B()
C()
}
type CReal struct {}
func (*CReal) A() {}
func (*CReal) B() {}
func (*CReal) C() {}
func main() {
fun1()
fun2()
}
func fun1() {
var file IReader = new(File)
file.Read([]byte{1,2,3})
var file1 IWriter = new(File)
file1.Write([]byte{1,2,3})
var file2 ICloser = new(File)
file2.Close()
}
func fun2() {
var a A = new(AReal)
var b B = new(BReal)
var c C = new(CReal)
a = b
b = a
a = c
b = c
}
注意
- 使用 type Name interface{} 来定义个接口
- 接口中的函数只能是定义,不能有实现
- 接口是非嵌入式的,只有有类实现了接口中的所有函数那么它就实现了这个接口
- 将对象实例赋值给接口,例如fun1() ,要求要被赋值的对象实例实现了接口要求的所有的方法
- 将接口A赋值给接口B: 在Go语言中,
- 只要两个接口拥有相同的方法列表(次序可忽略),那么他们是等同的,可以相互赋值
- 接口赋值并不要求两个接口必须等价,如果接口A 的方法列表是接口B的方法列表的子集,那么接口B的接口对象可以赋值给接口A的接口对象(接口B的方法中有接口A的所有方法)
- 例如:fun(2)