小编MSH*_*MSH的帖子

返回 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' …
Run Code Online (Sandbox Code Playgroud)

go

1
推荐指数
1
解决办法
3459
查看次数

标签 统计

go ×1