Last active
March 22, 2022 07:09
-
-
Save echohes/66658fecd083a4f07ff521cb2c3968d0 to your computer and use it in GitHub Desktop.
Golang Generics examples
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" | |
) | |
func main() { | |
var a, b uint | |
a = 1 | |
b = 10 | |
fmt.Println(max(a, b)) | |
} | |
type numOrder interface { | |
int | uint | int8 | int16 | int32 | |
} | |
func max[T numOrder](x, y T) T { | |
if x >= y { | |
return x | |
} | |
return y | |
} |
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" | |
"golang.org/x/exp/constraints" | |
) | |
func main() { | |
list := []int{1, 2, 3, 4} | |
a := 10 | |
fmt.Println(Contains(a, list)) | |
list2 := []string{"a", "b", "c", "d"} | |
y := "a" | |
fmt.Println(Contains(y, list2)) | |
} | |
func Contains[T constraints.Ordered](n T, list []T) bool { | |
for _, i := range list { | |
if n == i { | |
return true | |
} | |
} | |
return false | |
} |
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" | |
"golang.org/x/exp/constraints" | |
) | |
func main() { | |
var a, b uint | |
var i, j string | |
a = 12 | |
b = 56 | |
i = "abc" | |
j = "def" | |
fmt.Println(Max(a, b)) | |
fmt.Println(Max(i, j)) | |
} | |
func Max[T constraints.Ordered](x, y T) T { | |
if x >= y { | |
return x | |
} | |
return y | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment