4 ms·
Consider this function signature: func SomeAdditionFunction(arg1 int, arg2 int) { fmt.Println("Sum:", arg1 + arg2) } This function will only accept a pair
by jniedrauer 8y ago
Consider this function signature:
func SomeAdditionFunction(arg1 int, arg2 int) {
fmt.Println("Sum:", arg1 + arg2)
}
This function will only accept a pair of integers. In order to perform addition on floats or int64s or any other number type, you would need a separate function.
Go has the concept of an empty interface (interface{}) which can accept any type. But this is not really a generic because you have to assert that it is a specific type in order to be sure what it actually is at runtime. This function for example, will not compile:
func SomeAdditionFunction(arg1 interface{}, arg2 interface{}) {
fmt.Println("Sum:", arg1 + arg2)
}
But this will:
func SomeAdditionFunction(arg1 interface{}, arg2 interface{}) {
fmt.Println("Sum:", arg1.(int)+arg2.(int))
}
In a language like Java, I could write this function to accept any type for which the + operator is valid, and it would still be type safe at compile time. I would not need to assert the types like I did above.
- mseepgood 8y ago> In a language like Java, I could write this function to accept any type for which the + operator is valid, and it would still be type safe at compile time. I would not need to assert the types like I did above. Really? No. Not in Java. static <T extends Number> void someAdditionFunction(T arg1, T arg2) { System.out.println("Sum:", arg1 + arg2); } "error: bad operand types for binary operator '+'"
- erik_seaberg 8y agoYeah, it works with methods, but unfortunately arg1 + arg2 isn't implemented by calling a method on Number.
- dtech 8y agoThat's because + is a java built-in unavailable to normal types. Usually something like an add method is used instead. It does not detract from the underlying point.