lundi 11 septembre 2017

golang, create a variable from another one

I want to :

  1. Create a variable with the type of another one. The source variable is numeric (int, int16, float32, ...)
  2. Make some simple operations (+, -, ...) on this variable.

This code works fine :

package main

import (
  "fmt"
  "reflect"
)

func init1(v interface{}) interface{} {
    switch reflect.ValueOf(v).Kind() {
        case reflect.Int:
            return int(0)
        case reflect.Float32:
            return float32(0)
        case reflect.Float64:
            return float64(0)
    }
    return nil
}

func sum(x, y interface{}) interface{} {
    switch reflect.ValueOf(x).Kind() {
        case reflect.Int:
            return x.(int) + y.(int)
        case reflect.Float32:
            return x.(float32) + y.(float32)
        case reflect.Float64:
            return x.(float64) + y.(float64)
    }
    return nil
}

func main() {
    v0 := 222.33
    x0 := init1(v0)
    x0 = sum(x0, v0)
    x0 = sum(x0, v0)
    fmt.Printf("v=%v, x=%v type x=%T\n", v0, x0, x0)

    v1 := 33
    x1 := init1(v1)
    x1 = sum(x1, v1)
    x1 = sum(x1, v1)
    fmt.Printf("v=%v, x=%v type x=%T\n", v1, x1, x1)
}

Result :

v=222.33, x=444.66 type x=float64
v=33, x=66 type x=int

Is there a more elegant solution (without the two switch blocks) to do the same job ?

Thanks for your help.





Aucun commentaire:

Enregistrer un commentaire