Skip to content

Instantly share code, notes, and snippets.

@percybolmer
Last active January 27, 2022 19:09
Show Gist options
  • Save percybolmer/8c4dcb6f40b8ec87fe54484862e5dfa9 to your computer and use it in GitHub Desktop.
Save percybolmer/8c4dcb6f40b8ec87fe54484862e5dfa9 to your computer and use it in GitHub Desktop.
Example Of how decide on the data type
package main
import (
"fmt"
"reflect"
)
// 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
}
// 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
}
func main() {
result := Subtract(10,20)
// will Print int
fmt.Println(reflect.TypeOf(result))
result2 := Subtract[float32](10,20)
// will Print Float32
fmt.Println(reflect.TypeOf(result2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment