我想在 Golang 中嘗試聯合型別的實作,因為在這個答案
中
我嘗試了這個:
package main
import (
"fmt"
"math/rand"
"time"
)
type intOrString interface {
int | string
}
func main() {
fmt.Println(measure())
}
func measure[T intOrString]() T {
rand.Seed(time.Now().UnixNano())
min := 20
max := 35
temp := rand.Intn(max-min 1) min
switch {
case temp < 20:
return "low" //'"low"' (type string) cannot be represented by the type T
case temp > 20:
return T("high") //Cannot convert an expression of the type 'string' to the type 'T'
default:
return T(temp)
}
}
那么我如何將'string'或'int'型別的運算式轉換為'T'型別。
uj5u.com熱心網友回復:
您誤解了泛型的作業原理。對于您的函式,您必須在呼叫該函式時提供一個型別。就像fmt.Println(measure[string]()),所以在這種情況下,您希望從中得到 a string。如果你這樣稱呼它,measure[int]()那么你期望一個 int 結果。但是你不能在沒有型別引數的情況下呼叫它。泛型用于為不同型別共享相同邏輯的函式。
對于您想要的,您必須使用any結果,然后檢查它是字串還是整數。例子:
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
res := measure()
if v, ok := res.(int); ok {
fmt.Printf("The temp is an int with value %v", v)
}
if v, ok := res.(string); ok {
fmt.Printf("The temp is a string with value %v", v)
}
}
func measure() any {
rand.Seed(time.Now().UnixNano())
min := 20
max := 35
temp := rand.Intn(max-min 1) min
switch {
case temp < 20:
return "low"
case temp > 20:
return "high"
default:
return temp
}
}
或者如果您只想列印出來(并且不需要知道型別),您甚至不需要檢查它,只需呼叫fmt.Printf("The temp is %v", res).
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/453314.html
標籤:走
上一篇:回傳一組地圖golang
