猿问

Golang 容器/列表创建 FindAll 函数

我想知道这是否是创建“通用”(是的,我知道,GoLang 中的一个敏感词)列表并将其传递给 FindAll 函数的方法。


这是我的尝试:


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!\n\n")


    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\n", value)

        } else {

            fmt.Println("Huh! What's that?")

        }

    }


}

我已经玩了一段时间了,并认为在我说服自己它是正确的之前,我最好得到围棋专家的建议。


千万里不及你
浏览 234回答 1
1回答

蓝山帝景

代码原样很好,但你应该问自己两个问题:1. 为什么不应该使用类型化切片?(与显式类型相比,interface{} 性能较慢,尽管在 Go 1.7 中会大大提高)2.将您的特定类型实现为链表会更好吗?像这样的东西可以更有效:type IntList []intfunc (l IntList) Filter(fn func(v int) bool) IntList {&nbsp; &nbsp; var o IntList&nbsp; &nbsp; for _, v := range l {&nbsp; &nbsp; &nbsp; &nbsp; if fn(v) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; o = append(o, v)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return o}几乎总是有更好的替代方案container/list,但这完全取决于您的用例。
随时随地看视频慕课网APP

相关分类

Go
我要回答