簡體   English   中英

Go:在switch類型中將任何int值轉換為int64

[英]Go: cast any int value to int64 in type switch

我經常有一種情況,我期望一個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

我知道我可以通過反射使用reflect.ValueOf(v).Int()來做到這一點,但是不應該有一個更好(更reflect.ValueOf(v).Int() )的方法嗎?

更新:

提起了一個問題,Rob建議在這種情況下使用reflect

如果沒有更多的上下文,很難給你一個意見,但看起來你正試圖讓你的實現過於通用,這對那些主要使用更多動態語言或具有通用支持的人來說很常見。

Learning Go過程的一部分是學會接受它的類型系統,並且根據你來自哪里,它可能具有挑戰性。

通常,在Go中,您希望支持一種類型,它可以包含您需要處理的所有可能值。 在你的情況下,它可能是一個int64。

例如,看看數學包。 它只適用於int64,並期望使用它的任何人正確地對其進行類型轉換,而不是試圖轉換所有內容。

另一種選擇是使用類型無關的接口,就像排序包那樣。 基本上,任何類型特定的方法都將在您的包之外實現,並且您希望定義某些方法。

學習和接受這些屬性需要一段時間,但總的來說,它在可維護性和穩健性方面證明是好的。 接口確保您具有正交性,強類型確保您可以控制類型轉換,最終可能會導致錯誤以及內存中不必要的副本。

干杯

你想解決什么問題? 您描述的完整解決方案如下所示:

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
    }
}

使用反射包。 請注意,這可能比展開交換機要慢很多。

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
}

你可以這樣做...轉換為字符串,然后解析字符串。 不是很有效但緊湊。 我把這個例子放在Go操場上: http//play.golang.org/p/0MCbDfUSHO

package main

import "fmt"
import "strconv"

func Num64(n interface{}) int64 {
    s := fmt.Sprintf("%d", n)
    i,err := strconv.ParseInt(s,10,64)
    if (err != nil) {
        return 0
    } else {
        return i
    }
}

func main() {
    fmt.Println(Num64(int8(100)))
    fmt.Println(Num64(int16(10000)))
    fmt.Println(Num64(int32(100000)))
    fmt.Println(Num64(int64(10000000000)))
    fmt.Println(Num64("hello"))
}

// Outputs:
// 100
// 10000
// 100000
// 10000000000
// 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM