Created
March 24, 2022 03:09
-
-
Save JustinSDK/970d044cdbd2688e05f376df8fc7dcb7 to your computer and use it in GitHub Desktop.
Go 泛型:Map 實現
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 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