Go:在switch类型中将任何int值转换为int64

Eri*_*ner 15 casting go

我经常有一种情况,我希望int(任何类型int/int8/16/32/64),并使用类型开关检查它

switch t := v.(type) {
  case int, int8, int16, int32, int64:
    // cast to int64
  case uint, uint8, uint16, uint32, uint64:
    // cast to uint64
}
Run Code Online (Sandbox Code Playgroud)

现在我不能使用直接强制转换,因为t在这种情况下将是类型interface{}.case对于每种整数类型,我真的必须将其拆分为s吗?

我知道我可以通过反射使用reflect.ValueOf(v).Int(),但不应该有更好的(不那么冗长)的方式吗?

更新:

提起了一个问题,Rob建议reflect在这种情况下使用.

小智 24

如果没有更多的上下文,很难给你一个意见,但看起来你正试图让你的实现过于通用,这对那些主要使用更多动态语言或具有通用支持的人来说很常见.

Learning Go过程的一部分是学会接受它的类型系统,并且根据你来自哪里,它可能具有挑战性.

通常,在Go中,您希望支持一种类型,它可以包含您需要处理的所有可能值.在你的情况下,它可能是一个int64.

例如,看看数学包.它只适用于int64,并期望使用它的任何人正确地对其进行类型转换,而不是试图转换所有内容.

另一种选择是使用类型无关的接口,就像排序包那样.基本上,任何类型特定的方法都将在您的包之外实现,并且您希望定义某些方法.

学习和接受这些属性需要一段时间,但总的来说,它在可维护性和稳健性方面证明是好的.接口确保您具有正交性,强类型确保您可以控制类型转换,最终可能会导致错误以及内存中不必要的副本.

干杯

  • 我只是认为语言可以为这种情况提供`intish`等类型.这只是不必要的冗长. (2认同)

pet*_*rSO 13

你想解决什么问题?您描述的完整解决方案如下所示:

func Num64(n interface{}) interface{} {
    switch n := n.(type) {
    case int:
        return int64(n)
    case int8:
        return int64(n)
    case int16:
        return int64(n)
    case int32:
        return int64(n)
    case int64:
        return int64(n)
    case uint:
        return uint64(n)
    case uintptr:
        return uint64(n)
    case uint8:
        return uint64(n)
    case uint16:
        return uint64(n)
    case uint32:
        return uint64(n)
    case uint64:
        return uint64(n)
    }
    return nil
}

func DoNum64Things(x interface{}) {
    switch Num64(x).(type) {
    case int64:
        // do int things
    case uint64:
        // do uint things
    default:
        // do other things
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 开关盒不是多余的,类型是不同的. (4认同)
  • 我试图解决的问题是你刚刚列出的冗余交换机案例. (3认同)

fuz*_*fuz 7

使用反射包.请注意,这可能比展开交换机要慢很多.

switch t := v.(type) {
case int, int8, int16, int32, int64:
    a := reflect.ValueOf(t).Int() // a has type int64
case uint, uint8, uint16, uint32, uint64:
    a := reflect.ValueOf(t).Uint() // a has type uint64
}
Run Code Online (Sandbox Code Playgroud)