比如,我们定义了一个 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
	…
}

  

相关文章:

  • 2022-01-16
  • 2021-06-21
  • 2022-12-23
  • 2022-01-24
  • 2021-11-15
  • 2021-06-29
  • 2022-02-08
  • 2022-01-14
猜你喜欢
  • 2021-11-15
  • 2023-03-19
  • 2021-09-15
  • 2022-02-09
  • 2022-12-23
  • 2021-08-06
相关资源
相似解决方案