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)
}
相关推荐
GiraKoo10 分钟前
【GiraKoo】C++17的新特性
c++
Rockson15 分钟前
C++如何查询实时贵金属行情
c++·api
shenyan~15 分钟前
关于 c、c#、c++ 三者区别
开发语言·c++
DoraBigHead1 小时前
小哆啦解题记——映射的背叛
算法
mit6.8241 小时前
[vroom] docs | 输入与问题定义 | 任务与运输工具 | json
c++·自动驾驶
Heartoxx1 小时前
c语言-指针与一维数组
c语言·开发语言·算法
charlie1145141911 小时前
如何使用Qt创建一个浮在MainWindow上的滑动小Panel
开发语言·c++·qt·界面设计
孤狼warrior1 小时前
灰色预测模型
人工智能·python·算法·数学建模
京东云开发者1 小时前
京东零售基于国产芯片的AI引擎技术
算法
chao_7893 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode