golang 断言 + 类型转换

当传参是接口类型,需要强制类型转换,

如下:

package main

import "fmt"

type bbc struct {
	a int32
}

func main() {
	k(bbc{a:100})

}

func k(p interface{})  {
	if msg, ok := p.(bbc); ok {
		fmt.Println(msg.a)

	}
}

  或

package main

import "fmt"

type bbc struct {
	a int32
}

func main() {
	k(&bbc{a:100})    // 注意,这里对应的强制转化类型

}

func k(p interface{})  {
	if msg, ok := p.(*bbc); ok {
		fmt.Println(msg.a)

	}
}

  

猜你喜欢

转载自www.cnblogs.com/huangliang-hb/p/9754125.html