dongxibo2095 2015-09-04 19:19
浏览 5
已采纳

是否可以使用反射来做类似于类型开关的事情?

I need to do different things based on the type of the value being reflected.

value := reflect.ValueOf(someInterface)

I'd like to do something that has the following effect:

if <type of value> == <type1> {
    do something
} else if <type of value> == <type2> {
    do something
}

This is something similar to what a type switch does in go code.

  • 写回答

1条回答 默认 最新

  • douchun5976 2015-09-04 19:48
    关注

    If you are iterating over fields of a struct, you can use a type switch to perform different actions based off of the field's type:

    value := reflect.ValueOf(s)
    for i := 0; i < value.NumField(); i++ {
        field := value.Field(i)
        if !field.CanInterface() {
            continue
        }
        switch v := field.Interface().(type) {
        case int:
            fmt.Printf("Int: %d
    ", v)
        case string:
            fmt.Printf("String: %s
    ", v)
        }
    }
    

    https://play.golang.org/p/-B3PWMqWTo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度