一.copy函数
-
通过copy函数可以把一个切片内容复制到另一个切片中
-
Go语言标准库源码定义如下
-
第一个参数是目标切片,接收第二个参数内容
-
第二个参数是源切片,把内容拷贝到第一个参数中
-
// The copy built-in function copies elements from a source slice into a
// destination slice. (As a special case, it also will copy bytes from a
// string to a slice of bytes.) The source and destination may overlap. Copy
// returns the number of elements copied, which will be the minimum of
// len(src) and len(dst).
func copy(dst, src []Type) int
-
拷贝时严格按照脚标进行拷贝.且不会对目标切片进行扩容
二.代码示例
-
把短切片拷贝到长切片中
s1:=[]int {1,2}
s2:=[]int {3,4,5,6}
copy(s2,s1)
fmt.Println(s1)//输出:[1 2]
fmt.Println(s2)//输出:[1 2 5 6]
-
把长切片拷贝到短切片中
s1:=[]int {1,2}
s2:=[]int {3,4,5,6}
copy(s1,s2)
fmt.Println(s1)//输出:[3 4]
fmt.Println(s2)//输出:[3 4 5 6]
-
把切片片段拷贝到切片中
s1:=[]int {1,2}
s2:=[]int {3,4,5,6}
copy(s1,s2[1:])
fmt.Println(s1)//输出:[4 5]
fmt.Println(s2)//输出:[3 4 5 6]
三.使用copy完成删除元素
-
使用copy函数可以保证原切片内容不变
s := []int{1, 2, 3, 4, 5, 6, 7}
n := 2 //要删除元素的索引
newSlice := make([]int, n)
copy(newSlice, s[0:n])
newSlice = append(newSlice, s[n+1:]...)
fmt.Println(s) //原切片不变
fmt.Println(newSlice) //删除指定元素后的切片
二.sort包
-
Go语言标准库中sort提供了排序API
-
sort包提供了多种排序算法,这些算法是内部实现的,每次使用sort包排序时,会自动选择最优算法实现
-
插入排序
-
快速排序
-
堆排
-
-
sort包中最上层是一个名称为Interface的接口,只要满足sort.Interface类型都可以排序
// A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package. The methods require that the
// elements of the collection be enumerated by an integer index.
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
-
Go语言标准库默认提供了对int、float64、string进行排序的API
-
很多函数的参数都是sort包下类型,需要进行转换.
二.排序实现
-
对int类型切片排序
num := [] int{1, 7, 5, 2, 6}
sort.Ints(num) //升序
fmt.Println(num)
sort.Sort(sort.Reverse(sort.IntSlice(num))) //降序
fmt.Println(num)
-
对float64类型切片排序
f := [] float64{1.5, 7.2, 5.8, 2.3, 6.9}
sort.Float64s(f) //升序
fmt.Println(f)
sort.Sort(sort.Reverse(sort.Float64Slice(f))) //降序
fmt.Println(f)
-
对string类型切片排序
-
按照编码表数值进行排序
-
多字符串中按照第一个字符进行比较
-
如果第一个字符相同,比较第二个字符
-
s := []string{"我", "我是中国人", "a", "d", "国家", "你", "我a"}
sort.Sort(sort.StringSlice(s)) //升序
fmt.Println(s)
//查找内容的索引,如果不存在,返回内容应该在升序排序切片的哪个位置插入
fmt.Println(sort.SearchStrings(s, "你是"))
sort.Sort(sort.Reverse(sort.StringSlice(s)))
fmt.Println(s)