Interfaces versus generics
This section presents a program that increments a numeric value by one using interfaces and generics so that you can compare the implementation details.
The code of genericsInterfaces.go
illustrates the two techniques and contains the next code.
package main
import (
"fmt"
)
type Numeric interface {
int | int8 | int16 | int32 | int64 | float64
}
This is where we define a constraint named Numeric
for limiting the permitted data types.
func Print(s interface{}) {
// type switch
switch s.(type) {
The Print()
function uses the empty interface for getting input and a type switch to work with that input parameter.
Put simply, we are using a type switch to differentiate between the supported data types—in this case, the supported data types are just int
and float64
, which have to do with the implementation of the type switch. However, adding more data types requires code changes, which is not the most efficient...