Search⌘ K
AI Features

Interfaces vs. Generics

Explore the differences between interfaces and generics in Go by comparing code implementations that handle multiple data types. Understand how generics provide type safety and scalability over interfaces through constraints like Numeric, enabling more efficient and maintainable code.

We'll cover the following...

This lesson presents a program that increments a numeric value by one using interfaces and generics so that we can compare the implementation details.

Coding example

The interfaces.go code illustrates the two techniques and contains the next code:

Go (1.19.0)
package main
import (
"fmt"
)
type Numeric interface {
type int, int8, int16, int32, int64, float64
}

This is where we define a constraint named Numeric for limiting the permitted data types.

Go (1.19.0)
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 ...