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.
Yes, use generics to move the type assertion inside of the function.