sequences and iteration
arrays, slices, maps, range
Arrays
package main
import (
"fmt"
//"time"
)
func main() {
// array in Go in fixed-length ordered sequence of elements
var arr [3]int
fmt.Println(arr) // results all zeros
arr[2] = 2 // assign direct value
fmt.Println(arr)
fmt.Println(arr[2]) // print specific value by index
arr2 := [6]int{1,2,1,1,1,1} // can contain same elements and can initialize right away
fmt.Println(arr2)
// find length by len(arr)
// declare 2D array
arr4 := [2][2]int{{1,2},{2}}
fmt.Println(arr4)
// variable size array
x := [...]string{"shariq"}
}
Slices
The slice type is an abstraction built on top of Go's array type, and so to understand slices we must first understand arrays.
same like list in python
An array variable denotes the entire array; it is not a pointer to the first array element (as would be the case in C).
slices are array with better functionality
syntax [ ]T, type of the elements of the slice
A slice can be created with the built-in function called
make
, which has the signature,
func make([]T, len, cap) []T
A slice consists of three things -
A pointer (reference) to its array.
The length of the array that the slice contains.
The capacity (the maximum limit the slice can grow using append).
Question: Difference between slice with make and slice without make
Answer: Both are ok but the use of make to declare slice will allocate memory even if there are no elements while without make will not allocate. Typically used when size is not known.
package main
import (
"fmt"
//"time"
)
func main() {
// slices is a slice of a array in go, it is typically based on array but better than it
s := make([]int,4)
fmt.Println(s)
// we can now set its parameter
s[0] = 3 // and etc
// len(s) and cap(s) gives length and capacity of s
s = append(s, 3)
fmt.Println(s)
s = append(s, 3)
fmt.Println(s)
s = append(s, 5)
fmt.Println(s)
// copy slice
var c []int = s
//copy(c,s)
fmt.Println(c)
c = append(c, 23)
fmt.Println(s,c)
// literally slicing from array
l := s[2:5]
fmt.Println(l)
// 2-D slice
two = [][]string{1,2,23}
fmt.Println(two)
2d = make([][]string,4)
fmt.Println(2d)
}
Maps
hashes or dicts in other languages (python)
syntax is given by:
m := make(map[string]int)
Maps are not safe for concurrent use: it's not defined what happens when you read and write to them simultaneously. If you need to read from and write to a map from concurrently executing goroutines, the accesses must be mediated by some kind of synchronization mechanism. One common way to protect maps is with sync.RWMutex.
package main
import (
"fmt"
//"time"
)
func main() {
// maps
m := make(map[string]string)
m["name"] = "shariq"
m["address"] = "ancd"
fmt.Println(m)
fmt.Println(m["name"]) // to get value for a key
fmt.Println(len(m)) // get length
// declare and initialize map without make
n := map[string]int{"rollnum":1}
fmt.Println(n)
// add new key
n["class"] = 2
fmt.Println(n)
// delete(name of map variable, name of key)
}
Range
Range on arrays and slices provides both the index and value for each entry.
package main
import (
"fmt"
)
func main() {
// range is to iterate over elements in a variety of data structure
nums := []int{0,1,2,3,4,5} // arrays
sum := 0
for _, num := range nums{
sum += num
}
fmt.Println(sum)
for i,num := range nums{
if num == 3{
fmt.Println(i)
}
}
// key: value pair
k := map[string]string{"a":"apple", "b":"banana"}
// range in k data structure
for k,v := range k{
fmt.Printf("%s -> %s\n", k, v)
}
// range over strings iterate over unicode code points, first value is index of rune and second is rune itself
for t, s:= range "shariq"{
fmt.Println(t,s)
}
// typing chr(97) in python will result in unicode character
}
Last updated
Was this helpful?