Skip to content

Instantly share code, notes, and snippets.

@JustinSDK
Created March 24, 2022 03:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinSDK/970d044cdbd2688e05f376df8fc7dcb7 to your computer and use it in GitHub Desktop.
Save JustinSDK/970d044cdbd2688e05f376df8fc7dcb7 to your computer and use it in GitHub Desktop.
Go 泛型:Map 實現
package main
import "fmt"
func Map[T any](arr []T, fn func(T) T) []T {
newArr := make([]T, len(arr))
for i := 0; i < len(arr); i++ {
newArr[i] = fn(arr[i])
}
return newArr
}
func main() {
arr := []int{1, 2, 3, 4, 5}
arr2 := Map(arr, func(x int) int { return x * 2 })
fmt.Println(arr2) // [2 4 6 8 10]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment