何时反映.IsValid返回false? [英] When does reflect.IsValid return false?

查看:75
本文介绍了何时反映.IsValid返回false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 IsValid 函数感到好奇,因为在使用此函数期间,它从未返回过 false .那么何时返回否定结果?

I am curious about IsValid function, because during my use of this function, it never returned false. So when does it return a negative result?

推荐答案

作为文档code> reflect.IsValid() 说:

As the doc reflect.IsValid() says:

如果v为零值,则返回false.[...]大多数函数和方法从不返回无效值.如果是这样,则其文档会明确说明条件.

It returns false if v is the zero Value. [...] Most functions and methods never return an invalid value. If one does, its documentation states the conditions explicitly.

Value.IsValid()应该报告 reflect.Value 本身是否有效,而不是其包装的值(如果有).

Value.IsValid() is supposed to report whether the reflect.Value itself is valid, not the value it wraps (if any).

下面的所有示例均显示 false .您可以在游乐场上试用它们.

All the examples below print false. You can try them on the Go Playground.

最简单的示例是在零值 reflect.Value 的a>(这是 struct ):

The simplest example is calling IsValid() on the zero value of reflect.Value (which is a struct):

fmt.Println(reflect.Value{}.IsValid())

第二个最简单的示例是将 nil 传递给 reflect.ValueOf():

The 2nd simplest example is when passing nil to reflect.ValueOf():

fmt.Println(reflect.ValueOf(nil).IsValid())

另一个示例:从指针为 nil 开始,在这种情况下,没有指向"值, nil 指针指向无处.尝试使用 获得指向值的 reflect.Value > Value.Elem() 导致零 reflect.Value ,其 IsValid()方法将返回 false :

Another example: start with a pointer being nil, in this case there is no "pointed" value, a nil pointer points to nowhere. Attempting to get the reflect.Value of the pointed value using Value.Elem() results in a zero reflect.Value whose IsValid() method will return false:

var i *int
v := reflect.ValueOf(i)
v2 := v.Elem()
fmt.Println(v2.IsValid())

或一行:

fmt.Println(reflect.ValueOf((*int)(nil)).Elem().IsValid())

如果您调用 Value.Indirect() 在上述 reflect.Value()上:

fmt.Println(reflect.Indirect(v).IsValid())

或尝试使用 Value按名称获取不存在的结构字段.FieldByName() :

Or attempting to get a non-existing struct field by name using Value.FieldByName():

s := struct{}{}
fmt.Println(reflect.ValueOf(s).FieldByName("").IsValid())

或尝试使用 Value.MethodByName通过名称获取不存在的方法() :

Or attempting to get a non-existing method by name using Value.MethodByName():

fmt.Println(reflect.ValueOf(s).MethodByName("").IsValid())

或尝试使用 不存在的键从地图中获取值> Value.MapIndex() :

Or attempting to get a value from a map by a non-existing key using Value.MapIndex():

m := map[int]int{}
fmt.Println(reflect.ValueOf(m).MapIndex(reflect.ValueOf(3)).IsValid())

列表继续...

这篇关于何时反映.IsValid返回false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆