http://play.golang.org/p/y7G1fMSoVa
I am so sorry. I accidentally deleted my previous question. Here is my second try.
I know that Go does not support generic types but there should be a way to do this.
I am trying to add any type of two arguments and return the result using interface and type assertion. But I am stuck at
(+) is not defined in interface
can't think of what type I should return
This is my previous step.
func Add(val1, val2 interface{}) int {
new_a := val1.(int)
new_b := val2.(int)
return new_a + new_b
}
This give me the right answer but this is useless since I know the integer values will be passed. I want a function that does not know what would be given and return the addition accordingly to the given variable types.
Here is my second try and get stuck.
http://play.golang.org/p/-_jvvs09nl
func Add(val1, val2 interface{}) {
// var x interface{} = 7 // x has dynamic type int and value 7
// i := x.(int) // i has type int and value 7
// a := reflect.ValueOf(val1)
// b := reflect.ValueOf(val2)
// fmt.Println(a, b)
// <int Value> <int Value>
type_val1 := reflect.TypeOf(val1)
type_val2 := reflect.TypeOf(val2)
fmt.Println(type_val1, type_val2)
result1 := val1.(type_val1) // ERROR : type_val1 is not a type
result2 := val2.(type_val2) // ERROR : type_val2 is not a type
fmt.Println(result1, result2)