英文:
How to figure out if `value.FieldByName(name)` finds the field?
问题
我正在尝试弄清楚如何在下面的示例中停止程序的执行,当field
未找到时。
如果FieldByName(key)
返回一个零值,我该如何警告用户未找到该字段?
field := mutable.FieldByName(key)
// 在调用.Type()之前需要确定字段是否存在
if field.X == Y {
log.Fatalf("无法在Config对象中找到[%s]字段", key)
}
switch field.Type().Name() {
}
英文:
I'm trying to figure out how to stop the execution of my program when the field
is not found in the example below.
If FieldByName(key)
returns a zero Value how can I warn the user that the field was not found?
field := mutable.FieldByName(key)
// need to figure out if the field exists before calling .Type() on it
if field.X == Y {
log.Fatalf("Unable to find [%s] in Config object", key)
}
switch field.Type().Name() {
}
答案1
得分: 5
正如你已经提到的,reflect
包的**文档**中指出:
FieldByName 根据给定的字段名返回结构体字段。如果未找到字段,则返回零值 Value。
这与类型的零值不同。在**Value 的文档**中,我们可以读到:
零值 Value 表示没有值。它的 IsValid 方法返回 false,其 Kind 方法返回 Invalid,其 String 方法返回 "
",而其他所有方法都会引发 panic。大多数函数和方法都不会返回无效值。如果有一个函数返回无效值,它的文档会明确说明条件。
因此,虽然 Len
解决方案可能有效,但更具描述性的测试方式是:
if !field.IsValid() {
log.Fatalf("无法在 Config 对象中找到 [%s] 字段", key)
}
英文:
As you've already mentioned, the documentation for the reflect
package states:
>FieldByName returns the struct field with the given name. It returns the zero Value if no field was found
This is not the same as a type's zero value. Under the documentation for Value
, we can read:
>The zero Value represents no value. Its IsValid method returns false, its Kind method returns Invalid, its String method returns "<invalid Value>", and all other methods panic. Most functions and methods never return an invalid value. If one does, its documentation states the conditions explicitly.
So, while the Len
solution might work, a more descriptive way to test it is:
if !field.IsValid() {
log.Fatalf("Unable to find [%s] in Config object", key)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论