我想不出如何将int
转换为包含complex128
的泛型类型.下面是一个无法编译的示例,除非将complex128
注释掉:
package main
import "fmt"
type val interface {
int64 | float64 | complex128
}
func f[V val](a, b V) (c V) {
q := calc()
return a * b * V(q)
}
func calc() int {
// lengthy calculation that returns an int
return 1
}
func main() {
fmt.Printf("%v\n", f(int64(1), int64(2)))
}
这是从一个大得多的计算中简化出来的.我try 使用switch ,但我try 的每个语法似乎都遇到了这样或那样的阻力.
如何将a
和b
与一个整数相乘?
我曾try 在返回变量的类型上使用switch ,如any(c).(type)
,但例如,如果我有case complex128:
,则它拒绝允许complex
内建,因为它不返回V
.
如果没有complex128
,上面的代码将被编译.