1. 程式人生 > >Go/複合資料型別/切片-slice

Go/複合資料型別/切片-slice

##切片

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	//切片slice的建立
	arr := [...]int{0,1,2,3,4,5}
	arr1 := []int{0,1,2,3,4,5}
	arr2 := make([]int,6,8)
	arr3 := make([]int,6)
	fmt.Printf("長度len:%d, 容量cap:%d \n",len(arr),cap(arr))	//6 6
	fmt.Printf("長度len:%d, 容量cap:%d \n",len(arr1),cap(arr1))	//6 6
	fmt.Printf("長度len:%d, 容量cap:%d \n",len(arr2),cap(arr2))	//6 8
	fmt.Printf("長度len:%d, 容量cap:%d \n",len(arr3),cap(arr3)) //6 6

	//切片的擷取
	//下標 [low:high:max] [low,high)  len=high-low  cap=max-low
	s := arr[:]
	fmt.Printf("%v len:%d cap:%d \n",s,len(s),cap(s))	//[0 1 2 3 4 5] len:6 cap:6
	s = arr[1:3:6]
	fmt.Printf("%v len:%d cap:%d \n",s,len(s),cap(s))	//[1 2] len:2 cap:5
	s = arr[:5]
	fmt.Printf("%v len:%d cap:%d \n",s,len(s),cap(s))	//[0 1 2 3 4] len:5 cap:6
	s = arr[1:]
	fmt.Printf("%v len:%d cap:%d \n",s,len(s),cap(s))	//[1 2 3 4 5] len:5 cap:5

	//切片是指向底層"陣列"的指標
	fmt.Println(arr)	//[0 1 2 3 4 5]
	s1 := arr[1:5:6]
	s1[2] = 333
	fmt.Println(arr)	//[0 1 2 333 4 5]

	//追加
	var slice []int
	slice = append(slice,1)
	slice = append(slice,2)
	slice = append(slice,3)
	slice = append(slice,1)
	fmt.Println(slice)

	//copy
	src := []int{1,1}
	dest := []int{2,2,2,2,2}
	copy(dest,src)
	fmt.Println(dest)	//[1 1 2 2 2]

	//切片作為函式引數是引用傳遞
	ss := []int{1,2,3,4,5}
	initData(ss)
	bubbleSort(ss)
	fmt.Println(ss)
}

func initData(s []int){
	//設定隨機數種子
	rand.Seed(time.Now().UnixNano())
	for i,_ := range s{
		s[i] = rand.Intn(10)
	}
}

func bubbleSort(s []int){
	for i := 0; i < len(s)-1; i++{
		for j := 0; j < len(s)-1-i; j++{
			if s[j] > s[j+1] {
				s[j],s[j+1] = s[j+1],s[j]
			}
		}
	}
}