Created
December 3, 2024 11:54
-
-
Save Integralist/4ac5854116d0ccae632b42ba2ed2c2e4 to your computer and use it in GitHub Desktop.
[Golang Generic Slice Map function] #go #golang #slices #map #functional #generics
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
// https://play.golang.com/p/TbawROSRv8X | |
package main | |
import ( | |
"fmt" | |
"golang.org/x/net/idna" | |
) | |
func main() { | |
s := []string{"xn--6frz82g", "xn--9dbq2a", "xn--vhquv"} | |
fmt.Printf("%#v\n", s) | |
Map[string](s, func(zone string) string { | |
u, err := idna.ToUnicode(zone) | |
if err != nil { | |
return zone | |
} | |
return u | |
}) | |
fmt.Printf("%#v\n", s) | |
} | |
// Map takes a slice and a map function, | |
// then applies it to each element of the slice. | |
func Map[T any](s []T, m func(T) T) { | |
for i, e := range s { | |
s[i] = m(e) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment