gpt4 book ai didi

go - 如何确定 `value.FieldByName(name)` 是否找到该字段?

转载 作者:IT王子 更新时间:2023-10-29 01:55:40 29 4
gpt4 key购买 nike

在下面的示例中,当未找到 field 时,我正在尝试找出如何停止执行我的程序。

如果 FieldByName(key) 返回零值,我该如何警告用户未找到该字段?

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() {
}

最佳答案

正如您已经提到的, the documentation 对于 reflect 包状态:

FieldByName returns the struct field with the given name. It returns the zero Value if no field was found

这与类型的零值不同。在 the documentation for Value,我们可以读到:

The zero Value represents no value. Its IsValid method returns false, its Kind method returns Invalid, its String method returns "", and all other methods panic. Most functions and methods never return an invalid value. If one does, its documentation states the conditions explicitly.

因此,虽然 Len 解决方案可能有效,但一种更具描述性的测试方法是:

if !field.IsValid() {
log.Fatalf("Unable to find [%s] in Config object", key)
}

关于go - 如何确定 `value.FieldByName(name)` 是否找到该字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25193256/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com