小编Suz*_*ose的帖子

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

我无法弄清楚如何将 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.

没有 …

generics go complex-numbers

5
推荐指数
1
解决办法
544
查看次数

标签 统计

complex-numbers ×1

generics ×1

go ×1