[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

 

posted @   Zhentiw  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源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
点击右上角即可分享
微信分享提示