In Go, an array is a numbered sequence of elements of a specific length.
funcmain() {//Create an array hold exactly 5 ints.var a[5]int fmt.Println("emp:", a) a[4] =100 fmt.Println("set:", a) fmt.Println("get:", a[4]) fmt.Println("len:", len(a))//You can declare and initialize an array in one line! b := [5]int{1, 2, 3, 4, 5} fmt.Println("dcl:", b)var twoD [2][3]intfor i :=0; i <2; i++ {for j :=0; j <3; j++ { twoD[i][j] = i + j } } fmt.Println("2d: ", twoD)}
By default an array is zero-values
We can get and set value at an index using array[index] = value, array[index]
len() is builtin and returns the length of an array
Slices
Slices are an important data type in Go, giving a more powerful interface to sequence than arrays.
Unlike arrays, slices are typed only by the elements they contain.
funcmain() { s :=make([]string, 3) fmt.Println("emp", s) s[0] ="a" s[1] ="b" s[2] ="c fmt.Println("set:", s) fmt.Println("get:", s[2]) fmt.Println("len:", len(s)) s = append(s, "d") s = append(s, "e", "f") fmt.Println("aps:", s) //๋น์ฐํ len๋ ์ฌ์ฉใ ๊ฐ c := make([]string, len(s)) copy(c, s) fmt.Println("cpy:", c) l := s[2:5] fmt.Println("sl1:", l) l = s[:5] fmt.Println("sl2:", l) l = s[2:] fmt.Println("sl3:" l) t := []string{"g", "h", "i"} fmt.Println("dcl:", t) twoD := make([][]int, 3) for i := 0; i < 3; i++ { innerLen := i + 1 twoD[i] = make([]int, innerLen) for j := 0; j < innerLen; j++ { twoD[i][j] = i + j } } fmt.Println("2d: ", twoD)}
To create an empty slice with non-zero length, use the builtin make()
array์๋ ๋ค๋ฅด๊ฒ append ๋ ๊ฐ์ฉ ๊ฐ
Slices support a "slice" operator slice[low:high]
Maps
Maps are associative data type like hashes or dicts in other languages