我无法弄清如何将一个 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)))
}
这是从一个更大的计算简化而来。我尝试使用 switch,但无论我尝试的语法似乎都会遇到某种阻力。
如何用整数乘以 a
和 b
?
我尝试在返回变量类型上使用 switch,例如 any(c).(type)
,但是例如如果我有 case complex128:
,那么它拒绝允许使用 complex
内置函数,因为它不返回 V
。
没有 complex128
上述代码将会编译。
var temp any
和最后的temp.(V)
,所以我只需要添加两行。 - Suzu Hiroseswitch
中有一个float64
而不是一个default
。 - Suzu Hirosepanic: interface conversion: interface {} is nil, not [the_name_of_the_new_type]
。我无法想到一个单元测试来捕捉它。也许你应该添加一条注释以提醒未来的你。 ^_^ - Zeke Lu