Last active
April 22, 2022 07:52
-
-
Save JustinSDK/dff875d4810f335b2a13caafeddaca8a 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" | |
type Indicable interface { | |
Len() int | |
Idx(i int) any | |
} | |
type AnySlice []any | |
func (p AnySlice) Len() int { return len(p) } | |
func (p AnySlice) Idx(i int) any { return p[i] } | |
func Map(arr Indicable, mapper func(any) any) []any { | |
newArr := make([]any, arr.Len()) | |
for i := 0; i < arr.Len(); i++ { | |
newArr[i] = mapper(arr.Idx(i)) | |
} | |
return newArr | |
} | |
func main() { | |
arr := AnySlice([]any{1.0, 2.0, 3.0, 4.0, 5.0}) | |
arr2 := Map(arr, func(x any) any { return x.(float64) * 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