Learning GO [DAY-4]

Hello again!

Today I’m gonna discuss about Array slicing, dynamic arrays, looping use the range. Let us first dicsus about creating arrays,

Creating Arrays

Arrays are fixed size by default, however they can be made dynamic as per need wbout which we’ll see soon in this blog.

Syntax for creating fixed size array

arr := [3]int{1,4,8}

the above snippet creates an array of size 3 with th defined values.

The arrays can be sliced using the slice operator :. This is a useful feature to manipulate the array to our wish. The slicing operator works same as in Python as per my knowledge. So, I’m not gonna discuss about that further.

Syntax for Slicing an array

new_arr = arr[1:]
// The above slice assumes the staring point to index 1 and ending point to stretch till the length of the array

// output: {4,8}

new_arr1 = arr[:2]
// The above slice assumes the staring point to index 0 and ending point to the specified index

// output: {1,4}

Dynamically sized arrays

In Go dynmaically sized arrays can be created using the below syntax.

syntax

arr := []int{1,2,3,4,5}

The syntax looks same as an normal array, but we can omit the capacity/size.

There are again two ways to proceed with the dynmaic arrays,

  1. make() function
  2. append() after declaration

make() function

make() takes two arguments, the slice/array of the specified type and the size. This is useful when creating dynamically sized empty slices.

Example

size := 3
arr := make([]int, 3)
// This creates a empty slice/array with a capcaity of 3

append() after declaration

append() after declaration contains two steps,

  1. Declaration of slice/array
  2. appending to it using append() function

let’s see an example,

Example

var arr []int
// slice declaration

// arr looks like: []
arr = append(arr, 5)
// This statement appends 5 to the arr

// arr looks like: [5]

range looping an array

Instead of using a for loop, we can use range loop which is similar to range in Python.

We can loop using key-values and also by individual elements of the slices.

a simple range loop looks like below,

sliceArr := []int{1,2,3,4,5}
for _, element := range sliceArr {
    fmt.Println("element is:", element)
}

output

element is: 1
element is: 2
element is: 3
element is: 4
element is: 5

So that’s for today. Today I practiced the past two days of my learnings along with TDD. There’s still more to cover and I’ll be doing that for sure.

Thanks for your time.

Until then signing off,

~/CR08