数组和切片
语言切片是对数组的抽象。
简短方式来分别声明vendor1和vendor2这两个数组和切片变量:
vendor1:=[5]string{"C","i","s","c","o"} //数组
vendor2:=[]string{"H","u","a","w","e","i"} //切片
如果要以标准形式来声明vendor1和vendor2这两个数组和切片变量的话,写法如下:
varvendor1[5]string=[5]string{"C","i","s","c","o"}
varvendor2[]string=[]string{"H","u","a","w","e","i"}
re1:=append(vendor2,"haha") 切片中追加元素
re2:=strings.Join(vendor2,"") 转成字符串类型
vendor1Slice := vendor1[:] // 将数组转换为切片
var interfaces = make([]string,2,3) //make 方法声明切片
interfaces[0]="gi0/0/1"
interfaces[1]="gi0/0/2"
数据和切片是引用类型 修改切片时数组的值也会被修改 同理 修改数组的值那么切片对应的值 也将被修改
array := [10]int{0,1,2,3,4,5,6,7,8,9}
slice := array[3:7]
fmt.Println(slice)// [3 4 5 6]
fmt.Println(array//[0 1 2 3 4 5 6 7 8 9]
slice[0] =33
fmt.Println(slice)// [33 4 5 6]
fmt.Println(array)//[0 1 2 33 4 5 6 7 8 9]
但是如果 使用append 之后将会跟 array 断开联系
slice =append(slice,10)
fmt.Println(slice)//[0 1 2 33 4 5 6 7 8 9 10]
fmt.Println(array)//[0 1 2 33 4 5 6 7 8 9]
切片删除
func RemoveIndex(s[] int,index int) []int {
return append(s[:index],s[index+1:]...)
}
func main(){
slice:=[]int{0,1,2,3,4,5}
fmt.Println(slice)//[0 1 2 3 4 5]
slice=RemoveIndex(slice,3)
fmt.Println(slice)//[0 1 2 4 5]
}
append()函数除了可以为切片添加元素外,也可以用来将两个切片合并,方法是在要添加的切片后面加上"...",即这里s[index+1:]...后面的"..."
切片元素排序
package main
import(
"fmt"
"sort"
)
funcmain(){
ints: = []int{2,5,-1,30,-9}
fmt.Println("排序前:",ints)//排序前:[25-1 38 -9]
sort.Ints(ints)
fmt.Println("排序后:",ints)/排序后:[-9-1 25 30]
sort.Sort(sort.Reverse(sort.IntSlice(ints)))
fmt.Println("倒序后:",ints)//倒序后:[38 5 2 -1 -9]
floats := []float64{1.1,-0.2,3.5,-5.1}
fmt.Println("\n排序前:",floats)//排序前:[1.1 -0.2 3.5 -5.1]
sort.Float64s(floats)
fmt.Println("排序后:",floats)//排序后:[-5.1 -0.2 1.1 3.5]
sort.Sort(sort.Reverse(sort.Float64Slice(floats)))
fmt.Println("倒序后:",floats)//倒序后:[3.5 1.1 -0.2 -51]
strings := []string{"aa","a","A","Aa","aab"}
fmt.Println("\n排序前:",strings)//排序前:[aa a A Aa aab]
sort.Strings(strings)
fmt.Println("排序后:",strings)//排序后:[A Aa a aa aab]
sort.Sort(sort.Reverse(sort.StringSlice(strings)))
fmt.Println("倒序后:",strings)//倒序后:[aab aa a Aa A]
}