Go 自学:切片slices

以下代码展示了两种建立slice的方法。

我们可以使用sort函数给slice排序。

go 复制代码
package main

import (
	"fmt"
	"sort"
)

func main() {

	var fruitList = []string{"Apple", "Tomato", "Peach"}
	fmt.Printf("Type of fruitlist is %T\n", fruitList)

	fruitList = append(fruitList, "Mango", "Banana")
	fmt.Println(fruitList)

	fruitList = append(fruitList[:3])
	fmt.Println(fruitList)

	highScores := make([]int, 4)
	highScores[0] = 234
	highScores[1] = 945
	highScores[2] = 465
	highScores[3] = 867

	highScores = append(highScores, 555, 666, 321)

	fmt.Println(highScores)

	fmt.Println(sort.IntsAreSorted(highScores))
	sort.Ints(highScores)
	fmt.Println((highScores))
}

输出为:

Type of fruitlist is \[\]string

Apple Tomato Peach Mango Banana

Apple Tomato Peach

234 945 465 867 555 666 321

false

234 321 465 555 666 867 945

以下代码展示了如何根据index从slice中移除指定元素。

go 复制代码
package main

import (
	"fmt"
)

func main() {

	var courses = []string{"reactjs", "javascript", "swift", "python", "ruby"}
	fmt.Println(courses)
	var index int = 2
	courses = append(courses[:index], courses[index+1:]...)
	fmt.Println(courses)
}
相关推荐
geovindu1 小时前
go: Iterative Algorithms
开发语言·后端·算法·golang·迭代算法
kite01213 小时前
Go语言Map深度解析与最佳实践
开发语言·后端·golang
Zachery Pole3 小时前
CCF-CSP备战NO.7【队列】
算法
闪电悠米4 小时前
力扣hot100-48.旋转图像-转置翻转详解
算法·leetcode·职场和发展
满天星83035774 小时前
【算法】最长递增子序列(三种解法)
算法
hold?fish:palm4 小时前
kv存储主从复制的设计与实现
c++·redis·后端
啦啦啦啦啦zzzz4 小时前
算法:贪心算法
c++·算法·leetcode·贪心算法
charlie1145141915 小时前
现代C++工程实践 WeakPtr 实战(三):WeakPtrFactory 与「最后成员」惯用法
开发语言·c++·开源项目·现代c++
清泓y6 小时前
RAG 技术
算法·ai
阿慧今天瘦了嘛6 小时前
计算机组成原理概述:从硬件到软件的桥梁
计算机网络·算法