2016-09-26 43 views
2
// Filter returns a new slice holding only 
// the elements of s that satisfy f() 
func Filter(s []int, fn func(int) bool) []int { 
    var p []int // == nil 
    for _, v := range s { 
     if fn(v) { 
      p = append(p, v) 
     } 
    } 
    return p 
} 

我沒有我的想法如何使用此功能,任何幫助,將不勝感激。Golang博客片和內部

回答

1

https://play.golang.org/p/Asc4v08wDO

package main 

import "fmt" 

// Filter returns a new slice holding only 
// the elements of s that satisfy f() 
func Filter(s []int, fn func(int) bool) []int { 
    var p []int // == nil 
    for _, v := range s { 
     if fn(v) { 
      p = append(p, v) 
     } 
    } 
    return p 
} 

func odd(i int) bool { 
    return i%2 != 0 
} 

func even(i int) bool { 
    return !odd(i) 
} 

func main() { 
    v := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} 

    fmt.Println(Filter(v, odd)) 
    fmt.Println(Filter(v, even)) 
} 
+0

幫我,我有點糊塗了。 – location