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)
}
相关推荐
让我们一起加油好吗15 分钟前
【C++】封装红黑树模拟实现 set 和 map
linux·c++·set·map·红黑树
Mr.Ja18 分钟前
【LeetCode热题100】No.11——盛最多水的容器
算法·leetcode·贪心算法·盛水最多的容器
hsjkdhs21 分钟前
C++之类的继承与派生
开发语言·c++
冷徹 .30 分钟前
2024ICPC区域赛香港站
数据结构·c++·算法
爱好学习的青年人1 小时前
一文详解Go语言字符串
开发语言·后端·golang
沐怡旸1 小时前
【底层机制】std:: function 解决的痛点?是什么?如何实现?如何正确用?
c++·面试
浅川.251 小时前
xtuoj string
开发语言·c++·算法
韩非1 小时前
if 语句对程序性能的影响
算法·架构
用户916357440951 小时前
LeetCode热题100——15.三数之和
javascript·算法
ting_zh2 小时前
导数、偏导数与梯度:机器学习数学基础
算法·基础数学