我需要检查 interface 值是否为 `nil。
但是通过使用反射它给我一个错误:
reflect: call of reflect.Value.Bool on struct Value.
通过nil
,它不会为nil
值给出错误。
最佳答案
Interface是一对(type, value)
,当你比较一个interface和nil时,你是在比较这对(type, value)和nil。要仅比较接口(interface)值,您必须将其转换为结构(通过类型断言)或使用反射。
当你知道接口(interface)的类型时做一个类型断言
if i.(bool) == nil {
}
否则,如果你不知道接口(interface)的底层类型,你可能不得不使用反射
if reflect.ValueOf(i).IsNil() {
}
关于reflection - 在不使用反射的情况下检查 Go 中的接口(interface)值是否为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38070015/