判断struct的interface-type字段是否设置
php小编小新在这里分享一个关于判断struct的interface-type字段是否设置的技巧。在Go语言中,struct类型可以实现多个接口,通过判断interface-type字段是否设置,我们可以轻松判断一个struct是否实现了某个特定的接口。这个技巧非常实用,可以在代码中准确判断对象的类型,从而进行相应的处理。接下来,我们一起来看看具体的实现方法吧!
问题内容
给定一个结构体,其字段属于接口类型:
type a interface { foo() } type b interface { bar() } type container struct { fielda a fieldb b ... }
以及实现这些接口的结构:
type a struct {} func (*a) foo() {} func newa() *a { return &a{} } type b struct {} func (*b) bar() {} func newb() *b { return &b{} }
以及创建 container
实例但未显式设置所有字段的代码:
c := &container{} c.fielda = newa() // c.fieldb = newb() // <-- fieldb not explicitly set
使用反射,如何检测未显式设置的字段?
在运行时检查 fieldb 的值,vscode 愉快地报告该值为 nil
。同样,尝试调用 c.fieldb.bar() 将会因 nil 指针取消引用而发生恐慌。但反射不允许您测试 isnil,iszero 也不会返回 true:
func validateContainer(c *container) { tC := reflect.TypeOf(*c) for i := 0; i < tC.NumField(); i++ { reflect.ValueOf(tC.Field(i)).IsNil() // panics reflect.ValueOf(tC.Field(i)).IsZero() // always false reflect.ValueOf(tC.Field(i)).IsValid() // always true } }
解决方法
您应该检查 reflect.valueof(*c)
的字段,而不是 reflect.typeof(*c)
。
package main import ( "fmt" "reflect" ) func validatecontainer(c *container) { tc := reflect.typeof(*c) vc := reflect.valueof(*c) for i := 0; i < vc.numfield(); i++ { if f := vc.field(i); f.kind() == reflect.interface { fmt.printf("%v: isnil: %v, iszero: %v, isvalid: %v\n", tc.field(i).name, f.isnil(), f.iszero(), f.isvalid(), ) } } // tc.field(i) returns a reflect.structfield that describes the field. // it's not the field itself. fmt.printf("%#v\n", reflect.valueof(tc.field(0))) } type a interface{ foo() } type b interface{ bar() } type container struct { fielda a fieldb b } type a struct{} func (*a) foo() {} func newa() *a { return &a{} } func main() { c := &container{} c.fielda = newa() validatecontainer(c) }
输出:
FieldA: IsNil: false, isZero: false, IsValid: true FieldB: IsNil: true, isZero: true, IsValid: true reflect.StructField{Name:"FieldA", PkgPath:"", Type:(*reflect.rtype)(0x48de20), Tag:"", Offset:0x0, Index:[]int{0}, Anonymous:false}
以上是判断struct的interface-type字段是否设置的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Go语言中使用RedisStream实现消息队列时类型转换问题在使用Go语言与Redis...

Go爬虫Colly中的Queue线程问题探讨在使用Go语言的Colly爬虫库时,开发者常常会遇到关于线程和请求队列的问题。�...

GoLand中自定义结构体标签不显示怎么办?在使用GoLand进行Go语言开发时,很多开发者会遇到自定义结构体标签在�...

Go语言中字符串打印的区别:使用Println与string()函数的效果差异在Go...

Go语言中用于浮点数运算的库介绍在Go语言(也称为Golang)中,进行浮点数的加减乘除运算时,如何确保精度是�...

Go语言中结构体定义的两种方式:var与type关键字的差异Go语言在定义结构体时,经常会看到两种不同的写法:一�...

Go语言中哪些库是大公司开发或知名开源项目?在使用Go语言进行编程时,开发者常常会遇到一些常见的需求,�...
