I want to try the union type implementation in Golang as in this answer
I try this:
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)
}
}
so how I can convert an expression of the type 'string' or 'int' to the type 'T'.
CodePudding user response:
You misunderstand how generics work. For your function you must provide a type when you call the function. Like fmt.Println(measure[string]())
, so in this case you expect to get a string
from it. If you call it like measure[int]()
then you expect an int as a result. But you cannot call it without a type parameter. Generics are for function which share the same logic for different types.
For what you want, you must use any
as a result, then check it if it's a string or an int. Example:
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
}
}
Or if you want to just print it out (and don't need to know the type), you don't even need to check it, just call fmt.Printf("The temp is %v", res)
.