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)
}
相关推荐
一拳一个呆瓜9 分钟前
【MFC】对话框属性:X Pos(X位置),Y Pos(Y位置)
c++·mfc
一拳一个呆瓜28 分钟前
【MFC】对话框属性:Center(居中)
c++·mfc
AI 嗯啦30 分钟前
数据结构深度解析:二叉树的基本原理
数据结构·算法
hai_qin39 分钟前
十三,数据结构-树
数据结构·c++
和光同尘@1 小时前
66. 加一 (编程基础0到1)(Leetcode)
数据结构·人工智能·算法·leetcode·职场和发展
CHEN5_021 小时前
leetcode-hot100 11.盛水最多容器
java·算法·leetcode
songx_991 小时前
leetcode18(无重复字符的最长子串)
java·算法·leetcode
@areok@2 小时前
C++mat传入C#OpencvCSharp的mat
开发语言·c++·opencv·c#
小王C语言2 小时前
【C++进阶】---- map和set的使用
开发语言·c++
max5006002 小时前
实时多模态电力交易决策系统:设计与实现
图像处理·人工智能·深度学习·算法·音视频