比如,我们定义了一个 struct
type person struct { Name string `json:"name"` Age int `json:"age"` }
然后有一个函数为了通用性,函数返回值类型为 interface,但是某种情况我们知道这个函数是返回 person 类型的,我们就可以
person.(person).Name
来调用 person 类型里面的东西,因为 interface 类型直接调用会报错。
官网一个例子:
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 … }