Search code examples
gogenericscomplex-numbers

How can I convert an int to a generic type containing complex128 in Go?


I cannot work out how to convert an int to a generic type containing complex128. Here is an example which doesn't compile unless the complex128 is commented out:

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)))
}

This is simplified from a much larger calculation. I've tried using a switch but every syntax I have attempted seems to meet resistance of one kind or another.

How can I multiply a and b with an integer?

I have tried using a switch on the type of the return variable such as any(c).(type) but for example if I have case complex128: then it refuses to allow the complex builtin since it doesn't return a V.

Without the complex128 the above will compile.


Solution

  • This one works but it needs to list every type in the switch statement:

    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))
    }