3 回答

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個(gè)贊
在沒(méi)有更多上下文的情況下很難給您意見(jiàn),但看起來(lái)您試圖使您的實(shí)現(xiàn)過(guò)于通用,這對(duì)于主要使用更動(dòng)態(tài)語(yǔ)言或具有通用支持的人來(lái)說(shuō)很常見(jiàn)。
學(xué)習(xí)圍棋過(guò)程的一部分是學(xué)習(xí)接受它的類(lèi)型系統(tǒng),這取決于你來(lái)自哪里,它可能具有挑戰(zhàn)性。
通常,在 Go 中,您希望支持一種可以容納您需要處理的所有可能值的類(lèi)型。在您的情況下,它可能是 int64。
例如,看看 math 包。它僅適用于 int64,并希望任何使用它的人都能正確地對(duì)其進(jìn)行類(lèi)型轉(zhuǎn)換,而不是嘗試轉(zhuǎn)換所有內(nèi)容。
另一種選擇是使用類(lèi)型不可知的接口,就像 sort 包一樣。基本上,任何特定于類(lèi)型的方法都將在您的包之外實(shí)現(xiàn),并且您希望定義某些方法。
學(xué)習(xí)和接受這些屬性需要一段時(shí)間,但總的來(lái)說(shuō),最終證明它在可維護(hù)性和健壯性方面是好的。接口確保您具有正交性,強(qiáng)類(lèi)型確保您可以控制類(lèi)型轉(zhuǎn)換,這最終會(huì)導(dǎo)致錯(cuò)誤以及內(nèi)存中不必要的副本。
干杯

TA貢獻(xiàn)1963條經(jīng)驗(yàn) 獲得超6個(gè)贊
你想解決什么問(wèn)題?您描述的完整解決方案如下所示:
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
}
}
- 3 回答
- 0 關(guān)注
- 269 瀏覽
添加回答
舉報(bào)