Last active
January 27, 2022 19:09
-
-
Save percybolmer/8d63b3855ffd4c443d123b3e7c39ce01 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
type MyOwnInteger int | |
// 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() { | |
var myint MyOwnInteger | |
myint = 10 | |
result := Subtract(myint, 20) | |
// will Print main.MyOwnInteger | |
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