golang interface 类型变量当作某个具体类型使用

比如,我们定义了一个 struct

type person struct {
	Name string `json:"name"`
	Age int		`json:"age"`
}

  

然后有一个函数为了通用性,函数返回值类型为 interface,但是某种情况我们知道这个函数是返回 person 类型的,我们就可以

person.(person).Name

来调用 person 类型里面的东西,因为 interface 类型直接调用会报错。

 

参考:Type_assertions

官网一个例子:

var x interface{} = 7          // x has dynamic type int and value 7
i := x.(int)                   // i has type int and value 7

type I interface { m() }

func f(y I) {
	s := y.(string)        // illegal: string does not implement I (missing method m)
	r := y.(io.Reader)     // r has type io.Reader and the dynamic type of y must implement both I and io.Reader
	…
}

  

转载于:https://www.cnblogs.com/eleven24/p/9030976.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值