Move type assertion within function that returns any

217 Views Asked by At

I have the following example of generic Go function:

package main

func read(address uint16) any {

    switch address {
    case 1:
        return float64(0.5)
    case 2:
        return int(8)
    default:
        return "Hello"
    }

}

func main() {
    v1 := read(1)
    v2 := read(2)

    v1 = v1 / 2.5
    v2 = v2 * 4
}

which fails because of missing type assertion. See code on go.dev/play.

In order to avoid this, I may use type assertion as per Go tutorial on generics:

v1 = v1.(float64) / 2.5
v2 = v2.(int) * 4

to correctly provide the type. However, I would like to create a generic method to read sensor values. Both the user and the compiler know that if read(1) is called then a float64 is returned, the same goes if read(2) is called which always returns an integer.

Bottom line: is there any way I can avoid the type-assertion syntax outside the function read()?

The only ugly way I can think of is to have different read functions like readInt() and readFloat64(), but I'd rather keep a generic method for reading.

1

There are 1 best solutions below

0
Jewel in the mouth of a Tiger On

is there any way I can avoid the type-assertion syntax outside the function read()?

Yes, use generics to move the type assertion inside of the function.

func read[T any](address uint16) T {
    var result any
    switch address {
    case 1:
        result = float64(0.5)
    case 2:
        result = int(8)
    default:
        result = "Hello"
    }
    return result.(T)
}

func main() {
    v1 := read[float64](1)
    v2 := read[int](2)

    v1 = v1 / 2.5
    v2 = v2 * 4
    fmt.Println(v1, v2)
}