|
| 1 | + |
| 2 | +# Arrays 與 Slices |
| 3 | + |
| 4 | +在 golang 中,陣列類型資料類型主要有兩種 array 與 slice 。 |
| 5 | + |
| 6 | +## array |
| 7 | +array 是一種固定長度的資料陣列。在初始化時,就設定好長度,並且無法後續修改。 |
| 8 | + |
| 9 | +```golang= |
| 10 | +arr := [4]int{1,1,1,1} |
| 11 | +arr := [...]int{1,1,1,1} |
| 12 | +``` |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | +## slice |
| 17 | + |
| 18 | +slice 是則是一種動態長度的資料陣列。在初始化,可以設定好容量 capacity 。可以透過 append 新增資料到 slice 上。而實際上, slice 內部是指向一個 array 資料型態的參考,遇到超過預設 capacity 的資料量時,就會產生新的二倍於原本 capacity 的陣列實體,然後把 slice 參考更新。 |
| 19 | + |
| 20 | +```golang= |
| 21 | +slice := []int{1,1,1,1} |
| 22 | +// slice 的預設的 capcity 會是當下資料量長度,當不指定時 |
| 23 | +// slice 基本有3個屬性 ptr 指向目前資料陣列參照, len 代表當下資料長度, cap 代表當下最多容量。 |
| 24 | +``` |
| 25 | + |
| 26 | + |
| 27 | + |
| 28 | +# iteration |
| 29 | + |
| 30 | +```golang= |
| 31 | +stockAmountByDay := []int{200,210, 300,311} |
| 32 | +``` |
| 33 | +## loop over by index |
| 34 | + |
| 35 | +```golang= |
| 36 | +sliceLength := len(stockAmountByDay) |
| 37 | +for idx := 0; idx < sliceLength; idx++ { |
| 38 | + stockAmount := stockAmountByDay[idx] |
| 39 | + fmt.Printf("stockAmount = %d\n",stockAmount) |
| 40 | +} |
| 41 | +``` |
| 42 | +[iteration-slice-by-idx](https://go.dev/play/p/w_iYwtB6u6c) |
| 43 | + |
| 44 | +## loop over by range |
| 45 | + |
| 46 | +```golang= |
| 47 | +for _, stockAmount := range stockAmountByDay { |
| 48 | + fmt.Printf("stockAmount = %d\n",stockAmount) |
| 49 | +} |
| 50 | +``` |
| 51 | + |
| 52 | +[iteration-slice-by-range](https://go.dev/play/p/CYLQDp2p4mY) |
| 53 | + |
| 54 | +# operation |
| 55 | + |
| 56 | +## append |
| 57 | + |
| 58 | +```golang= |
| 59 | +stockAmountByDay = append(stockAmountByDay, 170) |
| 60 | +``` |
| 61 | + |
| 62 | +[append-example](https://go.dev/play/p/843TDDp3N6I) |
| 63 | + |
| 64 | +## sub range reference |
| 65 | +```golang= |
| 66 | +stockAmountByDayRange := stockAmountByDay[1:4] |
| 67 | +``` |
| 68 | + |
| 69 | + |
| 70 | +[sub-range-reference](https://go.dev/play/p/K9x8MOBA3gh) |
| 71 | + |
| 72 | + |
| 73 | +## copy |
| 74 | +```golang= |
| 75 | +stockAmountByRangeClone := make([]int, len(stockAmountByRange)) |
| 76 | +copy(stockAmountByRangeClone, stockAmountByRange) |
| 77 | +``` |
| 78 | + |
| 79 | + |
| 80 | + |
| 81 | +[copy-example](https://go.dev/play/p/4v2qE0jikrb) |
| 82 | + |
| 83 | + |
| 84 | +# 參考文件 |
| 85 | + |
| 86 | +[slice-intro](https://go.dev/blog/slices-intro) |
0 commit comments