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
	…
}

  

猜你喜欢

转载自www.cnblogs.com/eleven24/p/9030976.html
今日推荐