doutuzhuohao6449 2014-08-07 22:23
浏览 99
已采纳

如何确定value.FieldByName(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条回答 默认 最新

  • dongyi2425 2014-08-07 23:14
    关注

    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 "", 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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏