Go The Way 之接口的定义与赋值

package main

import "fmt"

/**
在Go 语言中,一个类只要实现了接口中的所有函数,则就说这个类实现了接口,没有像Java 必须使用implement 进行强制说明
 */

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
}
/**
以上代码 File 实现了 IReader、IWriter、ICloser 的接口,Go语言的非嵌入式接口
 */

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()  {
	/**
	接口赋值在Go 语言中分为如下两种情况:
	1. 将对象实例赋值给接口,例如fun1() ,要求要被赋值的对象实例实现了接口要求的所有的方法
	2. 将接口A赋值给接口B: 在Go语言中,
		(1)只要两个接口拥有相同的方法列表(次序可忽略),那么他们是等同的,可以相互赋值
		(2)接口赋值并不要求两个接口必须等价,如果接口A 的方法列表是接口B的方法列表的子集,那么接口B的接口对象可以赋值给接口A的接口对象(接口B的方法中有接口A的所有方法)
		例如:fun(2)
	*/
	fun1()
	fun2()
}

func fun1() {
	var file IReader  = new(File)
	file.Read([]byte{1,2,3}) //Read

	var file1 IWriter  = new(File)
	file1.Write([]byte{1,2,3}) //Write

	var file2 ICloser  = new(File)
	file2.Close() //Close
}

/**
接口赋值测试
 */
func fun2() {
	var a A = new(AReal)
	var b B = new(BReal)
	var c C = new(CReal)
	a = b
	b = a
	a = c
	// c = a 编译报错
	b = c
	// c = b 编译报错
}

注意
  • 使用 type Name interface{} 来定义个接口
  • 接口中的函数只能是定义,不能有实现
  • 接口是非嵌入式的,只有有类实现了接口中的所有函数那么它就实现了这个接口
  • 将对象实例赋值给接口,例如fun1() ,要求要被赋值的对象实例实现了接口要求的所有的方法
  • 将接口A赋值给接口B: 在Go语言中,
    • 只要两个接口拥有相同的方法列表(次序可忽略),那么他们是等同的,可以相互赋值
    • 接口赋值并不要求两个接口必须等价,如果接口A 的方法列表是接口B的方法列表的子集,那么接口B的接口对象可以赋值给接口A的接口对象(接口B的方法中有接口A的所有方法)
    • 例如:fun(2)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值