-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added some examples of generics in golang
- Loading branch information
Showing
1 changed file
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
// Generics from go 1.18 | ||
|
||
package main | ||
|
||
import ( | ||
"fmt" | ||
) | ||
|
||
// Type set, Contracts befor 1.18 | ||
type Num interface { | ||
int | float64 | ||
} | ||
|
||
func Summa[T Num](a, b T) T { | ||
return a + b | ||
} | ||
|
||
//func Concat[T any, U any](first T, second U) { | ||
func Concat[T any, U any](first T, second U) { | ||
fmt.Println(first, second) | ||
} | ||
|
||
func Distinct[T comparable](list []T) []T { | ||
uniq := make(map[T]bool) | ||
var result []T | ||
|
||
for _, i := range list { | ||
if !uniq[i] { | ||
uniq[i] = true | ||
result = append(result, i) | ||
} | ||
} | ||
return result | ||
} | ||
|
||
func PrintAny(items []any) { | ||
for _, item := range items { | ||
fmt.Printf("%v ", item) | ||
} | ||
fmt.Println("") | ||
} | ||
|
||
|
||
func main() { | ||
fmt.Println(Summa(5, 4)) | ||
fmt.Println(Summa(3.3, 8.1)) | ||
// fmt.Println(Summa("something", "in the water")) | ||
|
||
Concat(22, "Building number") | ||
|
||
fmt.Println(Distinct([]int{1, 4, 4, 6, 6, 6, 7, 9})) | ||
fmt.Println(Distinct([]string{"word", "word", "cat", "war", "dog", "people"})) | ||
|
||
PrintAny([]any{1, "some", true, 6.28}) | ||
|
||
} | ||
|