Golang 接口深入讨论

一 点睛

1 Golang 接口中不能有任何变量。

2 一个接口(比如 A 接口)可以继承多个别的接口(比如 B、C 接口),这时如果要实现 A 接口,也必须将 B、C 接口的方法也全部实现。

3 interface 类型默认是一个指针(引用类型),如果没有对 interface 初始化就使用,那么会输出 nil。

4 空接口 interface{} 没有任何方法,所以所有类型都实现了空接口, 即可以把任何一个变量赋给空接口。

二 代码

package main

import (
   "fmt"
)

type BInterface interface {
   test01()
}

type CInterface interface {
   test02()
}

type AInterface interface {
   BInterface
   CInterface
   test03()
}

// 如果需要实现 AInterface,就需要将 BInterface CInterface 的方法都实现
type Stu struct {
}

func (stu Stu) test01() {
}
func (stu Stu) test02() {
}
func (stu Stu) test03() {
}

type T interface {
}

func main() {
   // 一个接口(比如 A 接口)可以继承多个别的接口(比如 B,C 接口),这时如果要实现 A 接口,也必须将 B,C 接口的方法也全部实现
   var stu Stu
   var a AInterface = stu
   a.test01()

   // 空接口 interface{} 没有任何方法, 所以所有类型都实现了空接 口, 即我们可以 把任何一个变量 赋给空接口。
   var t T = stu // ok
   fmt.Println(t)
   var t2 interface{} = stu
   var num1 float64 = 8.8
   t2 = num1
   t = num1
   fmt.Println(t2, t)
}

三 测试

{}

8.8 8.8

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值