17

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
}

tこの場合は型になるため、今は直接キャストを使用できませんinterface{}case整数型ごとにこれを s に分割する必要がありますか?

を使用してリフレクションを介して実行できることはわかっていますが、これを行うためreflect.ValueOf(v).Int()のより良い(冗長でない)方法はありませんか?

アップデート:

問題を提出し、Robreflectはこの場合にのみ使用することを勧めました。

4

4 に答える 4

14

どのような問題を解決しようとしていますか? あなたが説明した完全なソリューションは次のようになります。

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
    }
}
于 2013-06-20T19:18:28.243 に答える