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)
}
相关推荐
qq_283720056 分钟前
C++ 基础:STL 原理介绍 + 实用技巧
c++·stl·c·模板库
量子炒饭大师8 分钟前
【C++模板进阶】——【非类型模板参数 / 模板的特化 / 模板分离编译】
开发语言·c++·dubbo·模板·非类型模板·模板的特化·模板分离编译
炽烈小老头10 分钟前
【每天学习一点算法 2026/03/29】搜索二维矩阵 II
学习·算法·矩阵
靴子学长16 分钟前
Qwen3.5 架构手撕源码
算法·架构·大模型
寒月小酒19 分钟前
3.28 OJ
算法
白藏y23 分钟前
【脚手架】Protobuf基础使用
c++·protobuf
南境十里·墨染春水27 分钟前
C++笔记 构造函数 析构函数 及二者关系(面向对象)
开发语言·c++·笔记·ecmascript
AI成长日志28 分钟前
【笔面试算法学习专栏】堆与优先队列专题:数组中的第K个最大元素与前K个高频元素
学习·算法·面试
OxyTheCrack1 小时前
【C++】一篇文章详解C++17新特性
c++
雅俗共赏1001 小时前
医学图像重建中常用的正则化分类
算法