我想尝试 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' …Run Code Online (Sandbox Code Playgroud) go ×1