我想尝试 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)
}
}
Run Code Online (Sandbox Code Playgroud)
那么我如何将“string”或“int”类型的表达式转换为“T”类型。
您误解了泛型的工作原理。对于您的函数,您必须在调用函数时提供类型。就像,所以在这种情况下你期望从中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
}
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您只想打印出来(并且不需要知道类型),您甚至不需要检查它,只需调用fmt.Printf("The temp is %v", res).
| 归档时间: |
|
| 查看次数: |
3459 次 |
| 最近记录: |