dongqian6234
dongqian6234
2016-05-17 15:05

Golang容器/列表创建FindAll函数

I was wondering if this is the way to create and pass 'generic'(yeah I know, a sensitive word in GoLang) lists to a FindAll function.

Here's my attempt:

package main

import (
    "container/list"
    "fmt"
    "strings"
)

func FindAll(lst *list.List, p func(interface{}) bool) *list.List {
    ans := list.New()

    for i := lst.Front(); i != nil; i = i.Next() {
        if p(i.Value) {
            ans.PushBack(i.Value)
        }
    }
    return ans
}

func ConvertToInt(p func(int) bool) func(interface{}) bool {
    return func(v interface{}) bool {
        if value, ok := v.(int); ok {
            if p(value) {
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    }
}

func IsEven(n int) bool {
    if n%2 == 0 {
        return true
    }
    return false
}

func ConvertoString(p func(s string) bool) func(interface{}) bool {
    return func(v interface{}) bool {
        if value, ok := v.(string); ok {
            if p(value) {
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    }
}

func IsHello(str string) bool {
    if strings.ToLower(str) == "hello" {
        return true
    } else {
        return false
    }
}

func main() {
    fmt.Println("Find All Programs!

")

    lsti := list.New()

    for i := 0; i < 11; i++ {
        lsti.PushBack(i)
    }

    ansIsEven := FindAll(lsti, ConvertToInt(IsEven))

    for i := ansIsEven.Front(); i != nil; i = i.Next() {
        if value, ok := i.Value.(int); ok {
            fmt.Printf("Found even: %d
", value)
        } else {
            fmt.Println("Huh! What's that?")
        }
    }

}

I've been playing with this for a while and thought I'd better get the advice of the Go experts before I convince myself its correct.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dpikoto468637 dpikoto468637 5年前

    The code as-is is pretty fine, but you should ask your self 2 questions:

    1. Why shouldn't you use a typed slice? (interface{} performance is slow compared to the explicit type, although it will greatly improve in Go 1.7)

    2. Would it be better to implement your specific type as a linked list?

    Something like this can be much more efficient:

    type IntList []int
    
    func (l IntList) Filter(fn func(v int) bool) IntList {
        var o IntList
        for _, v := range l {
            if fn(v) {
                o = append(o, v)
            }
        }
        return o
    }
    

    There's almost always a better alternative to container/list, however it all depends on your use case.

    点赞 评论 复制链接分享

为你推荐