[Go] Filter an Array in Go
Golang has no built-in function(s) to filter an array. This lesson will teach you two different ways to filter.
The first is to create a separate array and add the filtered elements to it. This works great, but doesn't use memory as efficiently as the second way.
The second way shows you how to filter by altering the original array in place without making another array to hold the filtered elements. But, it has a side-effect that I'll tell you about which may help you decide which approach you will use to filter your array.
package main
import (
"fmt"
"log"
)
func main() {
champions, err := loadChampions()
if err != nil {
log.Fatalf("An error occurred loading/parsing champions, err=%v", err)
}
fmt.Printf("There are %d total champions: %v\n\n", len(champions), champions)
brawlers := filter(champions, func(champ champion) bool {
return champ.hasClass("Brawler") && champ.Cost >= 3
})
fmt.Printf("Found %d brawlers, %v\n\n", len(brawlers), brawlers)
fmt.Printf("There are %d total champions: %v\n\n", len(champions), champions)
}
func filter(champs []champion, f filterFunc) []champion {
var result []champion
for _, champion := range champs {
if f(champion) {
result = append(result, champion)
}
}
return append
}
type filterFunc func(champion) bool
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2023-02-18 [CSS 3] Gap
2023-02-18 [React] Scaffold a React application with pnpm and vite
2023-02-18 [Typescript] Creating a Dynamic Function with Variable Arguments
2020-02-18 [Javascript] Primitive value are immutable
2020-02-18 [ML] 2. Introduction to neural networks
2020-02-18 【逻辑思维】同一律:白马到底是不是马
2019-02-18 [NPM] Avoid Duplicate Commands by Calling one NPM Script from Another