如果你一直在使用函数或动态编程语言,可能会觉得for循环和if语句会产生冗长的代码。用于处理列表的函数构造(例如map和filter)通常很有用,并使代码看起来更具可读性。但是,在Go标准库中很少支持类似的操作,并且在没有泛型或非常复杂的映射和使用空接口的情况下很难使用。本节将提供使用Go闭包实现集合的一些基本示例。

实践

创建collections.go :

package collections

// WorkWith会实现集合接口
type WorkWith struct {
    Data    string
    Version int
}

// Filter是一个过滤函数。
func Filter(ws []WorkWith, f func(w WorkWith) bool) []WorkWith {
    // 初始化返回值
    result := make([]WorkWith, 0)
    for _, w := range ws {
        if f(w) {
            result = append(result, w)
        }
    }
    return result
}

// Map是一个映射函数。
func Map(ws []WorkWith, f func(w WorkWith) WorkWith) []WorkWith {
    // 返回值的长度应该与传入切片长度一致
    result := make([]WorkWith, len(ws))

    for pos, w := range ws {
        newW := f(w)
        result[pos] = newW
    }
    return result
}

创建functions.go :

package collections

import "strings"

// LowerCaseData 将传入WorkWith的data字段变为小写
func LowerCaseData(w WorkWith) WorkWith {
    w.Data = strings.ToLower(w.Data)
    return w
}

// IncrementVersion 将传入WorkWith的Version加1
func IncrementVersion(w WorkWith) WorkWith {
    w.Version++
    return w
}

// OldVersion 返回一个闭包,用于验证版本是否大于指定的值
func OldVersion(v int) func(w WorkWith) bool {
    return func(w WorkWith) bool {
        return w.Version >= v
    }
}

创建main.go:

package main

import (
    "fmt"

    "github.com/agtorre/go-cookbook/chapter3/collections"
)

func main() {
    ws := []collections.WorkWith{
        {"Example", 1},
        {"Example 2", 2},
    }

    fmt.Printf("Initial list: %#v\n", ws)

    ws = collections.Map(ws, collections.LowerCaseData)
    fmt.Printf("After LowerCaseData Map: %#v\n", ws)

    ws = collections.Map(ws, collections.IncrementVersion)
    fmt.Printf("After IncrementVersion Map: %#v\n", ws)

    ws = collections.Filter(ws, collections.OldVersion(3))
    fmt.Printf("After OldVersion Filter: %#v\n", ws)
}

这会输出:

Initial list: []collections.WorkWith{collections.WorkWith{Data:"Example", Version:1}, collections.WorkWith{Data:"Example 2", Version:2}}
After LowerCaseData Map: []collections.WorkWith{collections.WorkWith{Data:"example", Version:1}, collections.WorkWith{Data:"example 2", Version:2}}
After IncrementVersion Map: []collections.WorkWith{collections.WorkWith{Data:"example", Version:2}, collections.WorkWith{Data:"example 2", Version:3}}
After OldVersion Filter: []collections.WorkWith{collections.WorkWith{Data:"example 2", Version:3}}

说明

Go中的闭包非常强大。虽然我们的集合函数不是通用的,但它们相对较小,并且很容易应用于WorkWith结构的各种函数。你可能会注意到我们在任何地方都没有返回错误。而且我们返回了一个全新的切片。

如果需要将修改层应用于列表或列表结构,则此模式可以为节省大量的操作并使测试变得非常简单。还可以将map和filter链接在一起,以获得非常富有表现力的编码风格。

最后编辑: kuteng  文档更新时间: 2021-01-03 15:03   作者:kuteng