在Go中如何将int转换为包含complex128的泛型类型?

Suz*_*ose 5 generics go complex-numbers

我无法弄清楚如何将 an 转换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)))
}
Run Code Online (Sandbox Code Playgroud)

这是从更大的计算中简化而来的。我尝试过使用开关,但我尝试过的每一种语法似乎都会遇到这样或那样的阻力。

如何将ab与一个整数相乘?

我尝试过在返回变量的类型上使用开关,但any(c).(type)例如如果我有case complex128:,那么它拒绝允许complex内置函数,因为它不返回V.

没有complex128上面的内容将编译。

Zek*_* Lu 4

这个可以工作,但需要列出switch语句中的每种类型:

func f[V val](a, b V) (c V) {
    q := calc()

    var temp any
    switch any(c).(type) {
    case complex128:
        temp = complex(float64(q), 0)
    case int64:
        temp = int64(q)
    default:
        temp = float64(q)
    }
    return a * b * (temp.(V))
}
Run Code Online (Sandbox Code Playgroud)