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)
}
相关推荐
万能程序员-传康Kk1 小时前
旅游推荐数据分析可视化系统算法
算法·数据分析·旅游
PXM的算法星球1 小时前
【并发编程基石】CAS无锁算法详解:原理、实现与应用场景
算法
ll7788111 小时前
C++学习之路,从0到精通的征途:继承
开发语言·数据结构·c++·学习·算法
烨然若神人~1 小时前
算法第十七天|654. 最大二叉树、617.合并二叉树、700.二叉搜索树中的搜索、98.验证二叉搜索树
算法
爱coding的橙子1 小时前
每日算法刷题Day2 5.10:leetcode数组1道题3种解法,用时40min
算法·leetcode
我不想当小卡拉米1 小时前
【Linux】操作系统入门:冯诺依曼体系结构
linux·开发语言·网络·c++
炎芯随笔1 小时前
【C++】【设计模式】生产者-消费者模型
开发语言·c++·设计模式
乌鸦9442 小时前
《类和对象(下)》
开发语言·c++·类和对象+
程序媛小盐2 小时前
贪心算法:最小生成树
算法·贪心算法·图论
Panesle2 小时前
分布式异步强化学习框架训练32B大模型:INTELLECT-2
人工智能·分布式·深度学习·算法·大模型