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)
}
相关推荐
喵星人工作室几秒前
C++火影忍者1.1.2
开发语言·c++
逻辑君14 分钟前
Foresight研究报告【20260011】
人工智能·线性代数·算法·矩阵
珊瑚里的鱼14 分钟前
【动态规划】不同路径Ⅱ
算法·动态规划
basketball61624 分钟前
C++ 中的 ptrdiff_t 详解
开发语言·c++
wunaiqiezixin32 分钟前
互斥锁与自旋锁的区别
c++
代码中介商42 分钟前
深入解析STL中的stack、queue与priority_queue
开发语言·c++
OxyTheCrack1 小时前
【Golang】简述make与new内置函数以及两者的区别
开发语言·golang
适应规律1 小时前
【无标题】
人工智能·python·算法
蒟蒻的贤1 小时前
关于文法G2算符优先分析的一个坑
算法
变量未定义~2 小时前
单调栈、单调队列(模板)、子矩阵、连通块中点的数量、堆箱子(4星)
算法