Skip to content

Instantly share code, notes, and snippets.

@percybolmer
Created January 9, 2022 14:34
Show Gist options
  • Save percybolmer/4078547ce452b15110a8219f08144f38 to your computer and use it in GitHub Desktop.
Save percybolmer/4078547ce452b15110a8219f08144f38 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
// Subtractable is a type constraint that defines subtractable datatypes to be used in generic functions
type Subtractable interface {
int | int32 | int64 | float32 | float64 | uint | uint32 | uint64
}
func main(){
var a int = 20
var b int = 10
result := Subtract(a, b)
var c float32 = 20.5
var d float32 = 10.3
result2 := Subtract(c, d)
fmt.Println("Result: ", result)
fmt.Println("Result2: ", result2)
}
// We define the Type parameter V, which is has a Constraint of Subtratacble
// We also say that function parameter a and b has the data type of V
// We then make the function return V
func Subtract[V Subtractable](a, b V) V {
return a - b
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment