Skip to content

Instantly share code, notes, and snippets.

@JustinSDK
Last active April 22, 2022 07:52
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/dff875d4810f335b2a13caafeddaca8a to your computer and use it in GitHub Desktop.
Save JustinSDK/dff875d4810f335b2a13caafeddaca8a to your computer and use it in GitHub Desktop.
Go 介面:Map 實現
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