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)
}
相关推荐
式5169 小时前
线性代数(七)主变量与特解
线性代数·算法
业精于勤的牙15 小时前
浅谈:算法中的斐波那契数(二)
算法·职场和发展
不穿格子的程序员15 小时前
从零开始写算法——链表篇4:删除链表的倒数第 N 个结点 + 两两交换链表中的节点
数据结构·算法·链表
liuyao_xianhui15 小时前
寻找峰值--优选算法(二分查找法)
算法
dragoooon3415 小时前
[hot100 NO.19~24]
数据结构·算法
神仙别闹16 小时前
基于QT(C++)实现学本科教务系统(URP系统)
数据库·c++·qt
deng-c-f16 小时前
Linux C/C++ 学习日记(49):线程池
c++·学习·线程池
ulias21216 小时前
C++ 的容器适配器——从stack/queue看
开发语言·c++
daidaidaiyu17 小时前
FFmpeg 关键的结构体
c++·ffmpeg
Tony_yitao17 小时前
15.华为OD机考 - 执行任务赚积分
数据结构·算法·华为od·algorithm