0
点赞
收藏
分享

微信扫一扫

slice添加map和filter方法

package main

import (
"fmt"
"strings"
)

// 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
}

// 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
}
}

func main() {
ws := []WorkWith{
{"Example", 1},
{"Example 2", 2},
}
fmt.Printf("Initial list: %#v\n", ws)
ws = Map(ws, LowerCaseData)
fmt.Printf("After LowerCaseData Map: %#v\n", ws)
ws = Map(ws, IncrementVersion)
fmt.Printf("After IncrementVersion Map: %#v\n", ws)
ws = Filter(ws, OldVersion(3))
fmt.Printf("After OldVersion Filter: %#v\n", ws)
}


举报

相关推荐

0 条评论