## 通過閉包實現集合操作
如果你一直在使用函數或動態編程語言,可能會覺得for循環和if語句會產生冗長的代碼。用于處理列表的函數構造(例如map和filter)通常很有用,并使代碼看起來更具可讀性。但是,在Go標準庫中很少支持類似的操作,并且在沒有泛型或非常復雜的映射和使用空接口的情況下很難使用。本節將提供使用Go閉包實現集合的一些基本示例。
### 實踐
1. 創建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
}
```
2. 創建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
}
}
```
3. 創建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)
}
```
4. 這會輸出:
```
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鏈接在一起,以獲得非常富有表現力的編碼風格。
* * * *
學識淺薄,錯誤在所難免。歡迎在群中就本書提出修改意見,以饗后來者,長風拜謝。
Golang中國(211938256)
beego實戰(258969317)
Go實踐(386056972)
- 前言
- 第一章 I/O和文件系統
- 常見 I/O 接口
- 使用bytes和strings包
- 操作文件夾和文件
- 使用CSV格式化數據
- 操作臨時文件
- 使用 text/template和HTML/templates包
- 第二章 命令行工具
- 解析命令行flag標識
- 解析命令行參數
- 讀取和設置環境變量
- 操作TOML,YAML和JSON配置文件
- 操做Unix系統下的pipe管道
- 處理信號量
- ANSI命令行著色
- 第三章 數據類型轉換和解析
- 數據類型和接口轉換
- 使用math包和math/big包處理數字類型
- 貨幣轉換和float64注意事項
- 使用指針和SQL Null類型進行編碼和解碼
- 對Go數據編碼和解碼
- Go中的結構體標簽和反射
- 通過閉包實現集合操作
- 第四章 錯誤處理
- 錯誤接口
- 使用第三方errors包
- 使用log包記錄錯誤
- 結構化日志記錄
- 使用context包進行日志記錄
- 使用包級全局變量
- 處理恐慌
- 第五章 數據存儲
- 使用database/sql包操作MySQL
- 執行數據庫事務接口
- SQL的連接池速率限制和超時
- 操作Redis
- 操作MongoDB
- 創建存儲接口以實現數據可移植性
- 第六章 Web客戶端和APIs
- 使用http.Client
- 調用REST API
- 并發操作客戶端請求
- 使用OAuth2
- 實現OAuth2令牌存儲接口
- 封裝http請求客戶端
- 理解GRPC的使用
- 第七章 網絡服務
- 處理Web請求
- 使用閉包進行狀態處理
- 請求參數驗證
- 內容渲染
- 使用中間件
- 構建反向代理
- 將GRPC導出為JSON API
- 第八章 測試
- 使用標準庫進行模擬
- 使用Mockgen包
- 使用表驅動測試
- 使用第三方測試工具
- 模糊測試
- 行為驅動測試
- 第九章 并發和并行
- 第十章 分布式系統
- 第十一章 響應式編程和數據流
- 第十二章 無服務器編程
- 第十三章 性能改進