Created
February 12, 2021 10:34
-
-
Save danielkraic/e7df7bd53cd6dbf049f59fe000f08ac7 to your computer and use it in GitHub Desktop.
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
package main | |
import ( | |
"fmt" | |
"strings" | |
) | |
type Country struct { | |
Code string | |
Name string | |
} | |
func (country Country) String() string { | |
return country.Code + ": " + country.Name | |
} | |
func Map[T any](items []T, mapper func(T) T) []T { | |
result := make([]T, 0, len(items)) | |
for _, item := range items { | |
result = append(result, mapper(item)) | |
} | |
return result | |
} | |
func Filter[T any](items []T, filter func(T) bool) []T { | |
var result []T | |
for _, item := range items { | |
if !filter(item) { | |
continue | |
} | |
result = append(result, item) | |
} | |
return result | |
} | |
func Find[T any](items []T, match func(T) bool) (*T, bool) { | |
for _, item := range items { | |
if match(item) { | |
return &item, true | |
} | |
} | |
var empty T | |
return &empty, false | |
} | |
func Print[T any](s []T) { | |
for _, v := range s { | |
fmt.Println(v) | |
} | |
} | |
func main() { | |
countries := []*Country{ | |
{Code: "SK", Name: "Slovakia"}, | |
{Code: "CZ", Name: "Czechia"}, | |
{Code: "HU", Name: "Hungary"}, | |
} | |
fmt.Println("all countries:") | |
Print(countries) | |
countries = Map(countries, func(country *Country) *Country { | |
return &Country{ | |
Code: strings.ToUpper(country.Code), | |
Name: strings.ToUpper(country.Name), | |
} | |
}) | |
sk, found := Find(countries, func(country *Country) bool { | |
return country.Code == "SK" | |
}) | |
if found { | |
fmt.Printf("\nSK found: %s\n", *sk) | |
} | |
fmt.Println("\nuppercase:") | |
Print(countries) | |
countries = Filter(countries, func(country *Country) bool { | |
return country.Code != "SK" | |
}) | |
fmt.Println("\nexcept SK:") | |
Print(countries) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment