return Golang 中的联合类型

return union type in Golang

我想尝试 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'.

类型

你误解了泛型的工作原理。对于您的函数,您必须在调用函数时提供类型。就像 fmt.Println(measure[string]()),所以在这种情况下,您希望从中得到一个 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)