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,

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.

Maps

  • hashes or dicts in other languages (python)

  • syntax is given by:

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.

source

Range

Range on arrays and slices provides both the index and value for each entry.

Last updated

Was this helpful?