vara[10]int// 宣告一個變數 a 為一個 int type 的 Array 並且長度只有10.(int 預設是 0, string 則為 nil)a:=[3]int{1}// [1 0 0]// 宣告一個變數 b 為 string type, 並且裡面的值是 A, B 並且長度只有 2b:=[2]string{"A","B"}b:=[...]string{"A","B"}// ... makes the compiler determine the lengtha:=[3][2]string// Multidimensional arraysa:=[3][2]string{{"lion","tiger"},{"cat","dog"},{"pigeon","peacock"},//this comma is necessary. The compiler will complain if you omit this comma}s:=[6]struct{iintbbool}{{2,true},{3,false},{5,true},{7,true},{11,false},{13,true},}// 透過 1: 2: 可指定 value 要塞的位置b:=[3]int{0:111,1:222,2:333,}// [111 222 333]b:=[...]int{3:333,}// [0 0 0 333]b:=[...]int{5:111,222,0:333,}// [333 0 0 0 0 111 222]
123456789101112131415161718192021222324252627
packagemainimport"fmt"funcmain(){vars[2]strings[0]="Hello"s[1]="World"fmt.Println(s)primes:=[6]int{2,3,5,7,11,13}fmt.Println(primes)a:=[...]float64{67.7,89.8,21,78}fori:=0;i<len(a);i++{fmt.Printf("%d th element of a is %.2f\n",i,a[i])}}/**[Hello World][2 3 5 7 11 13]0 th element of a is 67.701 th element of a is 89.802 th element of a is 21.003 th element of a is 78.00**/
Passing a array to a function
傳遞給 function 不會改變原來的值,因為 array 不是 reference types 而是 value types
123456789101112131415161718192021
packagemainimport"fmt"funcchangeLocal(num[5]int){num[0]=55fmt.Println("inside function ",num)}funcmain(){num:=[...]int{5,6,7,8,8}fmt.Println("before passing to function ",num)changeLocal(num)//num is passed by valuefmt.Println("after passing to function ",num)}/**before passing to function [5 6 7 8 8]inside function [55 6 7 8 8]after passing to function [5 6 7 8 8]**/
funcmain(){// `range` on strings iterates over Unicode code// points. The first value is the starting byte index// of the `rune` and the second the `rune` itself.fori,c:=range"go"{fmt.Println(i,c)}}// 0 103// 1 111
Slices
不用定義其最大長度,而且可以直接賦予值
An array has a fixed size. A slice, on the other hand, is a dynamically-sizeds
Slice: The size specifies the length. The capacity of the slice is
equal to its length. A second integer argument may be provided to
specify a different capacity; it must be no smaller than the
length. For example, make([]int, 0, 10) allocates an underlying array
of size 10 and returns a slice of length 0 and capacity 10 that is
backed by this underlying array.
Map: An empty map is allocated with enough space to hold the
specified number of elements. The size may be omitted, in which case
a small starting size is allocated.
Channel: The channel’s buffer is initialized with the specified
buffer capacity. If zero, or the size is omitted, the channel is
unbuffered.
123456789101112
// 範圍 low ~ hight -1a[low:high]// 也可以在加上 capa[low:high:cap][]int{1,2,3}//creates and array and returns a slice reference[]int{3:123,4:321,5:123456}// 指定 index,其餘的會是 0numa:=[3]int{78,79,80}nums1:=numa[:]//creates a slice which contains all elements of the array// tart and end are 0 and len(numa)
packagemainimport("fmt")funcmain(){s:=[]int{2,3,5,7,11,13}printSlice(s)s=s[:0]// Slice the slice to give it zero length.printSlice(s)s=s[:4]// Extend its length.printSlice(s)s=s[:cap(s)]// re-slicedprintSlice(s)s=s[2:]// Drop its first two values.printSlice(s)}funcprintSlice(s[]int){fmt.Printf("len=%d cap=%d %v\n",len(s),cap(s),s)}/**len=6 cap=6 [2 3 5 7 11 13]len=0 cap=6 []len=4 cap=6 [2 3 5 7]len=6 cap=6 [2 3 5 7 11 13]len=4 cap=4 [5 7 11 13]**/
re-sliced upto its capacity
12345678910111213141516
packagemainimport("fmt")funcmain(){fruitarray:=[...]string{"apple","orange","grape","mango","water melon","pine apple","chikoo"}fruitslice:=fruitarray[1:3]fmt.Printf("length of slice %d capacity %d\n",len(fruitslice),cap(fruitslice))fruitslice=fruitslice[:cap(fruitslice)]fmt.Println("After re-slicing length is",len(fruitslice),"and capacity is",cap(fruitslice))}// length of slice 2 capacity 6// After re-slicing length is 6 and capacity is 6
packagemainimport("fmt""strings")funcmain(){// Create a tic-tac-toe board.board:=[][]string{[]string{"_","_","_"},[]string{"_","_","_"},[]string{"_","_","_"},}// The players take turns.board[0][0]="X"board[2][2]="O"board[1][2]="X"board[1][0]="O"board[0][2]="X"fori:=0;i<len(board);i++{fmt.Printf("%s\n",strings.Join(board[i]," "))}}// X _ X// O _ X// _ _ O
packagemainimport("fmt")funcmain(){vars[]int//zero value of a slice is nilprintSlice(s)// append works on nil slices.s=append(s,0)printSlice(s)// The slice grows as needed.s=append(s,1)printSlice(s)// We can add more than one element at a time.s=append(s,2)printSlice(s)}funcprintSlice(s[]int){fmt.Printf("len=%d cap=%d %v\n",len(s),cap(s),s)}// len=0 cap=0 []// len=1 cap=2 [0]// len=2 cap=2 [0 1]// len=3 cap=4 [0 1 2]
use make function to create dynamically-sized arrays.
packagemainimport("fmt")funcsubtactOne(numbers[]int){fori:=rangenumbers{numbers[i]-=2}}funcmain(){nos:=[]int{8,7,6}fmt.Println("slice before function call",nos)subtactOne(nos)//function modifies the slicefmt.Println("slice after function call",nos)//modifications are visible outside}/**slice before function call [8 7 6]slice after function call [6 5 4]**/
make(map[key]value)value,ok:=map[key]// 判斷 key 的 value 在不在delete(map,key)
Map: An empty map is allocated with enough space to hold the
specified number of elements. The size may be omitted, in which case
a small starting size is allocated.
packagemainimport("fmt")funcfind(numint,nums...int){fmt.Printf("type of nums is %T\n",nums)found:=falsefori,v:=rangenums{ifv==num{fmt.Println(num,"found at index",i,"in",nums)found=true}}if!found{fmt.Println(num,"not found in ",nums)}fmt.Printf("\n")}funcmain(){find(89,89,90,95)find(45,56,67,45,90,109)find(78,38,56,98)find(87)// 相當於nums:=[]int{89,90,95}find(89,nums...)// 要加 ... 否則 type 會是 []int,造成 error}/**type of nums is []int89 found at index 0 in [89 90 95]type of nums is []int45 found at index 2 in [56 67 45 90 109]type of nums is []int78 not found in [38 56 98]type of nums is []int87 not found in []s**/
原理是會將,後面的參數轉成 slice,所以 type 會變成 []int,但是因為 find 後面接收的參數 type 是 int,也不能直接將 []int 帶進去,因此 []int 透過 ... 語法糖,帶到 Variadic Functions 裡
example 2
1234567891011121314151617
packagemainimport("fmt")funcchange(s...string){s[0]="Go"s=append(s,"playground")fmt.Println(s)// [Go world playground]}funcmain(){welcome:=[]string{"hello","world"}change(welcome...)fmt.Println(welcome)// [Go world]}