[Go - slice] Remove Elements from a slice in Go

Go has a special indexing syntax that forms the basis of removing one or more elements from a slice. I will teach you this syntax and show you its various forms.

Based upon that, I'll show you how to remove a single element from a slice. However, you may find this somewhat limiting. I also will show you a more typical example of removing elements from a slice as we iterate over it. This technique shows you how to remove multiple elements from a slice.

func main() {
	all, err := loadChampions()
	if err != nil {
		log.Fatalf("An error occurred loading/parsing champions, err=%v", err)
	}
    
    // get 0 to 19
	some := all[0:20]
    // get 0 to 19
	some = all[:20]
    // get 10 to the end
	some = all[10:]
    // get all
	some = all[:]

	// Remove an element from the slice by index
    // ... spread operator
    // since append expects individual elements as its second and subsequent arguments, 
    // the ... operator is used to expand the second slice (all[11:]) into a series of arguments
    // So the 10th element is removed
	most := append(all[0:10], all[11:]...)
    
    // Remove element with new slice
    var filtered []champion
    for _, champ := range all {
        if !champ.hasClass("Sorcerer") {
            filtered = append(filtered, champ)
        }
    }

	// Remove elements by altering the slice in place
	index := 0
	for _, champ := range all {
		if champ.hasClass("Sorcerer") {
			continue
		}

		all[index] = champ
		index++
	}

	all = all[:index]
}

 

posted @   Zhentiw  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2023-02-06 [Typescript] Global Scope
2023-02-06 [Typescript] Indexing an Object with Branded Types
2019-02-06 [TypeScript] Type Definitions and Modules
2019-02-06 [Tools] Add a Dynamic Tweet Button to a Webpage
2019-02-06 [Algorithm] Find Nth smallest value from Array
2018-02-06 [Javascript] Delegate JavaScript (ES6) generator iteration control
2017-02-06 [React] Use React.cloneElement to Extend Functionality of Children Components
点击右上角即可分享
微信分享提示