Go 接口

底层值为 nil 的接口值(接收者为nil)

即便接口内的具体值为 nil,方法仍然会被 nil 接收者调用。(一个空指针调用一个方法)

在一些语言中,这会触发一个空指针异常,但在 Go 中通常会写一些方法来优雅地处理它(如本例中的 M 方法)。

注意: 保存了 nil 具体值的接口其自身并不为 nil。

type T struct {
	S string
}

func (t *T) M() {
	if t == nil {
        //进行一个处理
		fmt.Println("<nil>")
		return
	}
	fmt.Println(t.S)
}

nil 接口值

nil 接口值既不保存值也不保存具体类型。

为 nil 接口调用方法会产生运行时错误,因为接口的元组内并未包含能够指明该调用哪个 具体 方法的类型。

下面的例子运行会panic

func main() {
	var i I
	describe(i)
	i.M()
}

空接口与断言

指定了零个方法的接口值被称为 *空接口:*

interface{}

空接口可保存任何类型的值。(因为每个类型都至少实现了零个方法。)

空接口被用来处理未知类型的值。例如,fmt.Print 可接受类型为 interface{} 的任意数量的参数。

package main

import (
	"fmt"
	)
//空接口主要用来接收位置类型变量
//空接口可保存任何类型的值。(因为每个类型都至少实现了零个方法。)
//
//空接口被用来处理未知类型的值。例如,fmt.Print 可接受类型为 interface{} 的任意数量的参数。
func main() {
	var i interface{}
	Des(i)
	i = 42
	Des(i)
	i = "luiz ckx"
	assertion(i)
	i = 1
	assertion(i)
	choose(1)
	choose("luiz")

}
func Des(i interface{}){
	fmt.Printf("{%v,%T}\n",i,i)
}
func assertion(i interface{}){
	//断言
	s,ok := i.(string)
	if ok {fmt.Println(s)
	} else {
		fmt.Println("unknow error")
	}
}
//用断言+switch进行判断(instance of)
func choose(i interface{}){
	switch v:=i.(type) {
	case int:
		fmt.Printf("Twice %v is %v\n", v, v*2)
	case string:
		fmt.Printf("%q is %v bytes long\n", v, len(v))
	default:
		fmt.Printf("I don't know about type %T!\n", v)
	}
}

练习:Stringer

通过让 IPAddr 类型实现 fmt.Stringer 来打印点号分隔的地址。

例如,IPAddr{1, 2, 3, 4} 应当打印为 "1.2.3.4"

package main

import (
	"fmt"
	"net"
)

type IpAddr[4]byte

func main() {
	hosts := map[string]IpAddr{
		"luiz": {127, 0, 0, 1},
		"ckx":  {192, 168, 0, 1},
	}

	for name,ip:= range hosts{
		fmt.Printf("%v: %v\n", name, ip)
	}

}

func (i IpAddr) String() string {
	s := i[:]
	return fmt.Sprintf((net.IP)(s).String())
}


package _interface

import (
	"fmt"
	"testing"
)

type dancer struct {
	item dance
}
type dance interface {
	Dance(string)
}

type poping struct {
	name string

}
func (p poping) Dance(s string) {
	fmt.Printf("%v\n",s)
	fmt.Println(p.name)
}
func TestName(t *testing.T) {
	d := dancer{}
	d.item = poping{`hello mtf was my name`}
	d.item.Dance("poping")
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值