In Go, an array is a numbered sequence of elements of a specific length.
func main() {
//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]int
for 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.
func main() {
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
func main() {
nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
sum += num
}
fmt.Println("sum:", sum)
//range๋ ์ธ๋ฑ์ค์ ๊ฐ ๋๊ฐ๋ฅผ ๋์์ ์ ๊ณตํ๋ค.
for i, num := range nums {
if num == 3 {
fmt.Println("index:", i_
}
}
kvs := map[string]string{"a": "apple", "b": "bannana"}
for k, v := range kvs {
fmt.Printf("%s -> %s\n", k, v)
}
//key๋ง ๋ฐ์์ค๋๊ฒ๋ ๊ฐ๋ฅํ๋ค.
for k := range kvs {
fmt.Println("key:", k}
}
for i, c := range "go" {
fmt.Println(i, c)
}
//์ ๊ธฐํ๊ฒ๋ ์ธ๋ฑ์ค์ ์ ๋์ฝ๋ ๊ฐ์ ๋ฐ
//0 103
//1 111
}
range on arrays and slices provides both index and value of each entry.
range on map iterates over key/value pairs.
range on strings iterates over Unicode code points.