【问题标题】:Convert interface from another interface type从另一个接口类型转换接口
【发布时间】:2021-07-22 00:38:08
【问题描述】:

我有一个通用函数,用于将目标设置为从地图中提取的值。目前,我对函数支持的所有类型都有一个大而丑陋的 switch 语句,但想知道是否有任何方法可以根据另一个接口的底层类型转换接口。

还有一个复杂的问题是这两个接口的类型不直接相关。目标接口是另一个接口的引用(例如,如果目标是 *int,则其他接口应转换为 int)。不要担心不遵循此模式的示例。

以下是我正在使用的功能:

    if iface, isSet := config[name]; isSet {
        if convert != nil {
            var err error
            if iface, err = convert(iface); err != nil {
                return err
            }
        }

        var isType bool
        switch target := target.(type) {
        case *string:
            *target, isType = iface.(string)
        case *bool:
            *target, isType = iface.(bool)
        case *int:
            *target, isType = iface.(int)
        case **int:
            *target, isType = iface.(*int)
        case *[]string:
            *target, isType = iface.([]string)
        case *strslice.StrSlice:
            *target, isType = iface.([]string)
        case *map[string]string:
            *target, isType = iface.(map[string]string)
        case *map[string]struct{}:
            *target, isType = iface.(map[string]struct{})
        case *time.Duration:
            *target, isType = iface.(time.Duration)
        case *nat.PortSet:
            *target, isType = iface.(map[nat.Port]struct{})
        case **container.HealthConfig:
            *target, isType = iface.(*container.HealthConfig)
        default:
            return fmt.Errorf("target must be a reference")
        }
        if !isType {
            t := reflect.TypeOf(target).String()
            return fmt.Errorf("%s should be type %s", name, t[1:])
        }
    }
    return nil
}

感谢您的帮助!

【问题讨论】:

  • @Flimzy 谢谢你的来信。我已更新问题以使用术语转换而不是转换
  • @Flimzy 函数做"type assertion"(不同于类型转换)。

标签: go interface casting type-inference


【解决方案1】:

使用反射 API:

// set sets the value pointed to target to value. 
func set(target interface{}, value interface{}) bool {
    t := reflect.ValueOf(target).Elem()
    v := reflect.ValueOf(value)
    if !v.Type().AssignableTo(t.Type()) {
        return false
    }
    t.Set(v)
    return true
}

在你的代码中使用这样的函数:

isType := set(target, iface)

【讨论】:

  • 非常好的解决方案。唯一的建议是 t.Set(t) 应该是 t.Set(v) 行,我在自己的代码中添加了检查目标或值是否为 nil,因为这会导致恐慌
  • 请注意,虽然反射允许更短的代码,但它会更慢。这对于许多用例来说都可以,但需要注意一些事项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-23
  • 2012-11-23
  • 1970-01-01
  • 2022-11-28
  • 2015-08-18
  • 2019-08-31
  • 2010-09-23
相关资源
最近更新 更多