array Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/array/ Sun, 02 May 2021 04:54:55 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 array Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/array/ 32 32 159787465 Convert singly linked list into an array using Go (Golang) https://vikasboss.github.io/linked-list-array-go/ https://vikasboss.github.io/linked-list-array-go/#comments Sun, 02 May 2021 04:52:38 +0000 https://vikasboss.github.io/?p=5564 Overview Convert singly linked list into an array using Golang Input singly linked list:  Output array:  Program Output:

The post Convert singly linked list into an array using Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Single List to Array Image

Overview

Convert singly linked list into an array using Golang

Input singly linked list: 

 "A" -> "B" -> "C" -> "D"

Output array: 

["A", "B", "C", "D"]

Program

package main

import "fmt"

type node struct {
	data string
	next *node
}

type singlyLinkedList struct {
	len  int
	head *node
}

func initList() *singlyLinkedList {
	return &singlyLinkedList{}
}

func (s *singlyLinkedList) AddFront(data string) {
	node := &node{
		data: data,
	}

	if s.head == nil {
		s.head = node
	} else {
		node.next = s.head
		s.head = node
	}
	s.len++
	return
}

func (s *singlyLinkedList) Size() int {
	return s.len
}

func (s *singlyLinkedList) Traverse() error {
	if s.head == nil {
		return fmt.Errorf("TraverseError: List is empty")
	}
	current := s.head
	for current != nil {
		fmt.Println(current.data)
		current = current.next
	}
	return nil
}

//Function to convert singly linked list to an array
func (s *singlyLinkedList) ToArray() []string {
	var myarr []string
	current := s.head
	for current.next != nil {
		fmt.Printf("\nAdding Element to array: %s", current.data)
		myarr = append(myarr, current.data)
		current = current.next
	}
	fmt.Printf("\nAdding Element to array: %s", current.data)
	myarr = append(myarr, current.data)
	return myarr
}

func main() {
	singleList := initList()
	fmt.Printf("AddFront: D\n")
	singleList.AddFront("D")
	fmt.Printf("AddFront: C\n")
	singleList.AddFront("C")
	fmt.Printf("AddFront: B\n")
	singleList.AddFront("B")
	fmt.Printf("AddFront: A\n")
	singleList.AddFront("A")

	fmt.Printf("Size: %d\n", singleList.Size())

	err := singleList.Traverse()
	if err != nil {
		fmt.Println(err.Error())
	}

	myarr := singleList.ToArray()
	fmt.Println()
	fmt.Println(myarr)
}

Output:

AddFront: D
AddFront: C
AddFront: B
AddFront: A
Size: 4
A
B
C
D

Adding Element to array: A
Adding Element to array: B
Adding Element to array: C
Adding Element to array: D
[A B C D]

The post Convert singly linked list into an array using Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/linked-list-array-go/feed/ 1 5564
Print an array or slice elements in Go (Golang) https://vikasboss.github.io/print-an-array-or-slice-elements-golang/ https://vikasboss.github.io/print-an-array-or-slice-elements-golang/#respond Mon, 18 May 2020 14:22:18 +0000 https://vikasboss.github.io/?p=2177 Overview The way we print an array or slice is same. Let’s look at both one by one Print a Slice Print slice elements together Using fmt.Println and fmt.Printf Output Print individual...

The post Print an array or slice elements in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

The way we print an array or slice is same. Let’s look at both one by one

Print a Slice

Print slice elements together

Using

  • fmt.Println and
  • fmt.Printf
package main
import "fmt"
func main() {
    numbers := []int{1, 2, 3}
    fmt.Println(numbers)
    fmt.Printf("Numbers: %v", numbers)
}

Output

[1 2 3]
Numbers: [1 2 3]

Print individual slice elements

Using

  • for-range loop
package main
import "fmt"
func main() {
    numbers := []int{1, 2, 3}
    for _, num := range numbers {
        fmt.Println(num)
    }
}

Output

1
2
3

Print a Array

Print array elements together

Using

  • fmt.Println and
  • fmt.Printf
package main
import "fmt"
func main() {
    numbers := [3]int{1, 2, 3}
    fmt.Println(numbers)
    fmt.Printf("Numbers: %v", numbers)
}

Output

[1 2 3]
Numbers: [1 2 3]

Print individual array elements:

Using

  • for-range loop
package main
import "fmt"
func main() {
    numbers := [3]int{1, 2, 3}
    for _, num := range numbers {
        fmt.Println(num)
    }
}

Output

1
2
3

The post Print an array or slice elements in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/print-an-array-or-slice-elements-golang/feed/ 0 2177
Two Dimensional (2d) and Multi-Dimensional Array and Slice in Go (Golang) https://vikasboss.github.io/two-dimensional-array-slice-golang/ https://vikasboss.github.io/two-dimensional-array-slice-golang/#respond Fri, 15 May 2020 21:25:39 +0000 https://vikasboss.github.io/?p=2146 In go multi-dimension is possible for both array and slice. Let’s see both of them in detail. Multi-Dimensional Arrays Overview Below is the format for declaring a multidimensional dimensional array where len1...

The post Two Dimensional (2d) and Multi-Dimensional Array and Slice in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
In go multi-dimension is possible for both array and slice. Let’s see both of them in detail.

Multi-Dimensional Arrays

Overview

Below is the format for declaring a multidimensional dimensional array

[len1][len2][len3]....[lenN]T{}

where

  • len1 , len2 .. lenN are length of each of the dimensions
  • T is the data type

All the rules that apply to the one-dimensional array also apply to the multidimensional array as well. It is also possible to specify the array elements during the declaration. In case the array elements are not specified during declaration, then all the array elements are allotted the default zero value of the <data_type>

Below is the format for declaring a two dimensional array with array elements specified.

var sample = [len1][len2]T{{a11, a12 .. a1y},
                       {a21, a22 .. a2y},
                       {.. },
                       {ax1, ax2 .. axy}}     

where

  • len1 denotes the number of rows
  • len2 denotes the number of columns
  • aij denotes an element present at i row and j column
  • T is the data type

Let’s see a small example illustrating above points:

package main

import "fmt"

func main() {

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

    fmt.Printf("Number of rows in array: %d\n", len(sample))
    fmt.Printf("Number of columns in array: %d\n", len(sample[0]))
    fmt.Printf("Total number of elements in array: %d\n", len(sample)*len(sample[0]))

    fmt.Println("Traversing Array")
    for _, row := range sample {
        for _, val := range row {
            fmt.Println(val)
        }
    }
}

Output

Number of rows in array: 2
Number of columns in array: 3
Total number of elements in array: 6
Traversing Array
1
2
3
4
5
6

Notice in the above program how are we able to get the number of rows, column and also the total number of elements in the array

  • Number of rows = len(sample)
  • Number of columns = len(sample[0])
  • Number of total elements = len(sample)*len(sample[0])

The same idea can be extended to three dimensions, four dimensions, and so on. Let’s see a small example of three dimensional array as well. In below program we are creating a 2*2*3 dimensional array.

package main

import "fmt"

func main() {
    sample := [2][2][3]int{{{1, 2, 3}, {4, 5, 6}}, {{7, 8, 9}, {10, 11, 12}}}

    fmt.Printf("Length of first dimension: %d\n", len(sample))
    fmt.Printf("Length of second dimension: %d\n", len(sample[0]))
    fmt.Printf("Length of third dimension: %d\n", len(sample[0][0]))

    fmt.Printf("Overall Dimension of the array: %d*%d*%d\n", len(sample), len(sample[0]), len(sample[0][0]))
    fmt.Printf("Total number of elements in array: %d\n", len(sample)*len(sample[0])*len(sample[0][0]))

    for _, first := range sample {
        for _, second := range first {
            for _, value := range second {
                fmt.Println(value)
            }
        }
    }
}

Output

Length of first dimension: 2
Length of second dimension: 2
Length of third dimension: 3
Overall Dimension of the array: 2*2*3
Total number of elements in array: 12
1
2
3
4
5
6
7
8
9
10
11
12

Accessing elements of a multi dimensional array

An element of a multi-dimensional array can be accessed using the index of each of the dimensions. For example, a two-dimensional array can be accessed by provided its row index and column index. Once we are able to access them using the index of each of the dimensions, then it is also possible to assign a new value to it as well. Let’s see a program

package main

import "fmt"

func main() {
    sample := [2][3]int{{1, 2, 3}, {4, 5, 6}}
    //Print array element
    fmt.Println(sample[0][0])
    fmt.Println(sample[0][1])
    fmt.Println(sample[0][2])
    fmt.Println(sample[1][0])
    fmt.Println(sample[1][1])
    fmt.Println(sample[1][2])
    
    //Assign new values
    sample[0][0] = 6
    sample[0][1] = 5
    sample[0][2] = 4
    sample[1][0] = 3
    sample[1][1] = 2
    sample[1][2] = 1

    fmt.Println()
    fmt.Println(sample[0][0])
    fmt.Println(sample[0][1])
    fmt.Println(sample[0][2])
    fmt.Println(sample[1][0])
    fmt.Println(sample[1][1])
    fmt.Println(sample[1][2])
}

Output

1
2
3
4
5
6

6
5
4
3
2
1

Traversal of a multidimensional array

A multidimensional array can be traversed using:

  • for-range loop
  • for loop

Let’s see a code example for traversal of a two dimensional array.

package main

import "fmt"

func main() {
    sample := [2][3]int{{1, 2, 3}, {4, 5, 6}}
    fmt.Println("Using for-range")
    for _, row := range sample {
        for _, val := range row {
            fmt.Println(val)
        }
    }

    fmt.Println("\nUsing for loop")
    for i := 0; i < 2; i++ {
        for j := 0; j < 3; j++ {
            fmt.Println(sample[i][j])
        }
    }

    fmt.Println("\nUsing for loop - Second way")
    for i := 0; i < len(sample); i++ {
        for j := 0; j < len(sample[i]); j++ {
            fmt.Println(sample[i][j])
        }
    }
}

Output

Using for-rage
1
2
3
4
5
6

Using for loop
1
2
3
4
5
6

Using for loop 
1
2
3
4
5
6

Some points to note about above program

  • We have to use a nested range for traversal using a for-range loop. The first range traverses each of the rows. The second range traverses the individual array present at that row
  • The same goes for iterating using for loop.
  • len(sample) gives the number of rows.
  • len(sample[i]) gives the number of columns present at row i.
  • The same idea can be extended to three dimensional, four-dimensional array element too.

How multidimensional array is stored in memory

Memory allocated for array is contiguous irrespective of weather an array is one dimensional or two dimensional. For example in case of two dimension array the second row starts in memory where the first row ends. Let's see a program illustrating this point

package main

import "fmt"

func main() {
    sample := [2][3]byte{}

    fmt.Println("First row")
    fmt.Println(&sample[0][0])
    fmt.Println(&sample[0][1])
    fmt.Println(&sample[0][2])

    fmt.Println("\nSecond row")
    fmt.Println(&sample[1][0])
    fmt.Println(&sample[1][1])
    fmt.Println(&sample[1][2])
}

Output

First row
0xc0000b4002
0xc0000b4003
0xc0000b4004

Second row
0xc0000b4005
0xc0000b4006
0xc0000b4007

Notice all the address are contiguous. And the second row starts where the first row ends.

Multi-dimensional Slices

Overview

As the multidimensional array is an array of arrays, similarly multi-dimensional slice is a slice of slices. To understand this, let's first look at the definition of a slice. A slice points to an underlying array and is internally represented by a slice header. A slice header is a struct which looks like  this

type SliceHeader struct {
        Data uintptr
        Len  int
        Cap  int
}

Data field in slice header is pointer to the underlying array. For a one dimensional slice, we have below declaration

oneDSlice := make([]int, 2)

To declare a two dimensional slice the declaration would be

twoDSlice := make([][]int, 2)

Above declaration means that we want to create a slice of 2 slices. Carefully understand this point. But wait a second here, we haven't specified the second dimension here, meaning what is the length of each of the inner 2 slices. In case of slice, each of the inner slice has to be explicitly intialised like below

for i := range twoDSlice {
    twoDSlice[i] = make([]int, 3)
}

So using range on the original slice, we specify the length each of 2 slices using make.  Below is one other way of doing the same but with slice elements specified

var twoDSlice = make([][]int, 2)
twoDSlice[0] = []int{1, 2, 3}
twoDSlice[1] = []int{4, 5, 6}

Basically, with the above declaration, we create a slice of 2*3 dimensions which is a two-dimensional slice. The same idea can be extended to two-dimension, three-dimension, and so on.

A complete working example of above two points

package main

import "fmt"

func main() {
    twoDSlice1 := make([][]int, 3)
    for i := range twoDSlice1 {
        twoDSlice1[i] = make([]int, 3)
    }
    fmt.Printf("Number of rows in slice: %d\n", len(twoDSlice1))
    fmt.Printf("Number of columns in arsliceray: %d\n", len(twoDSlice1[0]))
    fmt.Printf("Total number of elements in slice: %d\n", len(twoDSlice1)*len(twoDSlice1[0]))
    fmt.Println("First Slice")
    for _, row := range twoDSlice1 {
        for _, val := range row {
            fmt.Println(val)
        }
    }
    twoDSlice2 := make([][]int, 2)
    twoDSlice2[0] = []int{1, 2, 3}
    twoDSlice2[1] = []int{4, 5, 6}
    fmt.Println()
    fmt.Printf("Number of rows in slice: %d\n", len(twoDSlice2))
    fmt.Printf("Number of columns in arsliceray: %d\n", len(twoDSlice2[0]))
    fmt.Printf("Total number of elements in slice: %d\n", len(twoDSlice2)*len(twoDSlice2[0]))
    fmt.Println("Second Slice")
    for _, row := range twoDSlice2 {
        for _, val := range row {
            fmt.Println(val)
        }
    }
}

Output

Number of rows in slice: 2
Number of columns in arsliceray: 3
Total number of elements in slice: 6
First Slice
0
0
0
0
0
0

Number of rows in slice: 2
Number of columns in arsliceray: 3
Total number of elements in slice: 6
Second Slice
1
2
3
4
5
6

We mentioned above that we are creating a two-dimensional slice of 2*3 dimensions.  With that said the thought that might be coming to your mind is whether it is possible to have different lengths for inner slices. Yes, it is possible. Unlike arrays which have inner arrays of the same length, in case of slice since we initialize each of the inner slices individually, it is possible to have different length for inner slices

Let's see an example

package main

import "fmt"

func main() {
    twoDSlice := make([][]int, 2)
    twoDSlice[0] = []int{1, 2, 3}
    twoDSlice[1] = []int{4, 5}
  
    fmt.Printf("Number of rows in slice: %d\n", len(twoDSlice))
    fmt.Printf("Len of first row: %d\n", len(twoDSlice[0]))
    fmt.Printf("Len of second row: %d\n", len(twoDSlice[1]))
    fmt.Println("Traversing slice")
    for _, row := range twoDSlice {
        for _, val := range row {
            fmt.Println(val)
        }
    }
}

Output

Number of rows in slice: 2
Len of first row: 3
Len of second row: 2
Traversing slice
1
2
3
4
5

Let's see a small example of a three-dimensional slice as well. In the below program, we are creating a slice of 2*2*3 dimensions.

package main

import "fmt"

func main() {
    sample := make([][][]int, 2)
    for i := range sample {
        sample[i] = make([][]int, 2)
        for j := range sample[i] {
            sample[i][j] = make([]int, 3)
        }
    }
    
    fmt.Printf("Length of first dimension: %d\n", len(sample))
    fmt.Printf("Length of second dimension: %d\n", len(sample[0]))
    fmt.Printf("Length of third dimension: %d\n", len(sample[0][0]))
    fmt.Printf("Overall Dimension of the slice: %d*%d*%d\n", len(sample), len(sample[0]), len(sample[0][0]))
    fmt.Printf("Total number of elements in slice: %d\n", len(sample)*len(sample[0])*len(sample[0][0]))
    for _, first := range sample {
        for _, second := range first {
            for _, value := range second {
                fmt.Println(value)
            }
        }
    }
}

Output

Length of first dimension: 2
Length of second dimension: 2
Length of third dimension: 3
Overall Dimension of the slice: 2*2*3
Total number of elements in slice: 12
0
0
0
0
0
0
0
0
0
0
0

Accessing Multi-Dimensional Slice elements

Accessing slice elements is the same as accessing elements of an array. Let's see an example

package main

import "fmt"

func main() {
    sample := make([][]int, 2)
    sample[0] = []int{1, 2, 3}
    sample[1] = []int{4, 5, 6}

    //Print array element
    fmt.Println(sample[0][0])
    fmt.Println(sample[0][1])
    fmt.Println(sample[0][2])
    fmt.Println(sample[1][0])
    fmt.Println(sample[1][1])
    fmt.Println(sample[1][2])

    //Assign new values
    sample[0][0] = 6
    sample[0][1] = 5
    sample[0][2] = 4
    sample[1][0] = 3
    sample[1][1] = 2
    sample[1][2] = 1

    fmt.Println()
    fmt.Println(sample[0][0])
    fmt.Println(sample[0][1])
    fmt.Println(sample[0][2])
    fmt.Println(sample[1][0])
    fmt.Println(sample[1][1])
    fmt.Println(sample[1][2])
}

Output

1
2
3
4
5
6

6
5
4
3
2
1

Traversal of a multi dimensional slice.

Traversing a multidimensional slice is the same as traversing a multi-dimensional array. A multidimensional slice can be traversed using

  • for-range loop
  • for loop

Let's see an example:

package main

import "fmt"

func main() {
    sample := make([][]int, 2)
    sample[0] = []int{1, 2, 3}
    sample[1] = []int{4, 5, 6}
    fmt.Println("Using for-range")
    for _, row := range sample {
        for _, val := range row {
            fmt.Println(val)
        }
    }

    fmt.Println("\nUsing for loop - Second way")
    for i := 0; i < len(sample); i++ {
        for j := 0; j < len(sample[i]); j++ {
            fmt.Println(sample[i][j])
        }
    }
}

Output

How multidimensional slice is stored in memory

Since in the case of the slice, each of the inner slices is initialized separately hence it is possible that inner slice might not be contiguous in memory with respect to each other. Although each of the elements within each of inner slice will be at the contiguous location. Let's see a program illustrating this point.

package main

import "fmt"

func main() {
    sample := make([][]byte, 2)
    sample[0] = make([]byte, 3)

    //testVariable := "s"
    //fmt.Println(testVariable)
    
    sample[1] = make([]byte, 3)

    fmt.Println("First row")
    fmt.Println(&sample[0][0])
    fmt.Println(&sample[0][1])
    fmt.Println(&sample[0][2])

    fmt.Println("\nSecond row")
    fmt.Println(&sample[1][0])
    fmt.Println(&sample[1][1])
    fmt.Println(&sample[1][2])
}

Output

First row
0xc000018072
0xc000018073
0xc000018074

Second row
0xc000018080
0xc000018081
0xc000018082

Please Note: There is a caveat in the above program. Since the second inner slice is initialized just after the first inner slice, there is a possibility that the address allotted to both of them is contiguous. It can happen but not always. Uncomment the line for test variable and then both the inner slice will not be allotted contiguous address. In the case of an array, all inner arrays will be stored at contiguous locations always.

Conclusion

This is all about multidimensional array and slice in golang. I hope you have liked this article. Please share the feedback in the comments.

The post Two Dimensional (2d) and Multi-Dimensional Array and Slice in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/two-dimensional-array-slice-golang/feed/ 0 2146
Understanding Array in Go (Golang) – Complete Guide https://vikasboss.github.io/understanding-array-golang-complete-guide/ https://vikasboss.github.io/understanding-array-golang-complete-guide/#comments Wed, 13 May 2020 19:52:44 +0000 https://vikasboss.github.io/?p=2137 This is the  chapter 17 of the golang comprehensive tutorial series. Refer to this link for other chapters of the series – Golang Comprehensive Tutorial Series Next Tutorial – SlicePrevious Tutorial – Struct Now let’s check...

The post Understanding Array in Go (Golang) – Complete Guide appeared first on Welcome To Golang By Example.

]]>
This is the  chapter 17 of the golang comprehensive tutorial series. Refer to this link for other chapters of the series – Golang Comprehensive Tutorial Series

Next Tutorial – Slice
Previous Tutorial – Struct

Now let’s check out the current tutorial. Below is the table of contents for current tutorial.

Overview

Similar to any other programming language, golang also has array data structure. But in go, arrays behave little differently than other languages and also we have something called slice in golang which is like a reference to an array. In this article, we will study only array.

Definition

An array is a contiguous collection of elements of the same type. It is an ordered sequence of elements stored contiguously in memory

Here is the format for the declaration of an array

sample := [size_of_array]{type}{a1, a2... an}
  • size_of_array – number of elements in the array
  • <type> is type of each element in the array
  • a1, a2 … an are the actual elements.

In golang, the size of the array is part of its type. So  This means that two arrays that have a different number of elements are of two different types and one cannot be assigned to another. Below error will be raised in case we try to assign two arrays of different length

cannot use sample1 (type [1]int) as type [2]int in assignment

The code is:

sample1 := [1]int{1}
sample2 := [2]int{1,2}

sample2 = sample1

For the same reason the length of array is fixed during create and cannot be changed later.

Declaration of an array

Both number of elements and actual elements are optional in the array declaration.

In below example, we see 4 ways of declaring of an array

  • Specifying both the length of the array and actual elements. Eg.
[2]int{1, 2}
  • Only length – In this case all the actual elements are filled up with default value zero of that type. Eg
[2]int{}
  • Only actual elements – In this case, the length of array will be equal to the number of actual elements. The symbol ‘…’ needs to be used within square brackets like this […] when not specifying the length. The symbol is an instruction to the compiler to calculate the length.
[...]int{2, 3}
  • Without length and actual elements – an empty array will be created in this case. Similar to above the symbol ‘…’ also needs to be used in this case as well.
[...]int{}

Let’s see a code example illustrating above points. Also please keep in mind that the builtin function len() can be used to calculate the length of an array. In below program we are using len() function to calculate the length of the array.

package main

import "fmt"

func main() {
    //Both number of elements and actual elements
    sample1 := [2]int{1, 2}
    fmt.Printf("Sample1: Len: %d, %v\n", len(sample1), sample1)

    //Only actual elements
    sample2 := [...]int{2, 3}
    fmt.Printf("Sample2: Len: %d, %v\n", len(sample2), sample2)

    //Only number of elements
    sample3 := [2]int{}
    fmt.Printf("Sample3: Len: %d, %v\n", len(sample3), sample3)

    //Without both number of elements and actual elements
    sample4 := [...]int{}
    fmt.Printf("Sample4: Len: %d, %v\n", len(sample4), sample4)
}

Output

Sample1: Len: 2, [1 2]
Sample2: Len: 2, [2 3]
Sample3: Len: 2, [0 0]
Sample4: Len: 0, []

Notice in the above example that for sample3 variable the actual elements are filled up with the default value of int which is 0.

It is also ok if the actual elements specified are less than the length of the array. The rest of the elements are filled up with the default value of the type specified. See the below example. The length of the array specified is 4 while only 2 actual elements are declared. Hence the remaining two elements are assigned value 0 which is the default zero value of an int.

package main

import "fmt"

func main() {
    sample := [4]int{5, 8}
    fmt.Printf("Sample: Len: %d, %v\n", len(sample), sample)
}

Output

Sample: Len: 4, [5 8 0 0]

Accessing array elements

Since array element are stored in contiguous manner, we can access an array element using an index. Similarly individual array elements can also be assigned a value using index. Accessing out of bound index will cause a compilation error. See below examples illustrating these points. The first index position will be zero and last will (length_of_array-1)

package main

import "fmt"

func main() {
    sample := [2]string{"aa", "bb"}

    fmt.Println(sample[0])
    fmt.Println(sample[1])

    sample[0] = "xx"
    fmt.Println(sample)
    //sample[3] = "yy"
}

Output

aa
bb
[xx bb]

On uncommenting the below line

sample[3] = "yy"

, it will give compilation error

invalid array index 3 (out of bounds for 2-element array)

Arrays are value in go

Array are value type in go. So an array variable name is not a pointer to the first element in fact it denotes the entire array. A copy of the array will be created when

  • An array variable is assigned to another array variable.
  • An array variable is passed as an argument to a function.

Let’s see above point with another example

package main

import "fmt"

func main() {
    sample1 := [2]string{"a", "b"}
    fmt.Printf("Sample1 Before: %v\n", sample1)
    sample2 := sample1
    sample2[0] = "c"
    fmt.Printf("Sample1 After assignment: %v\n", sample1)
    fmt.Printf("Sample2: %v\n", sample2)
    test(sample1)
    fmt.Printf("Sample1 After Test Function Call: %v\n", sample1)
}
func test(sample [2]string) {
    sample[0] = "d"
    fmt.Printf("Sample in Test function: %v\n", sample)
}

Output

Sample1 Before: [a b]
Sample1 After assignment: [a b]
Sample2: 
Sample in Test function: [d b]
Sample1 After Test Function Call: [a b]

In above example,

  • we assigned the sample1 to sample2 and we then changed 0th index at sample2 to have a different value.  After that when we print sample1, we see that it hasn’t changed. This is because when we assign sample1 to sample2, a copy is created and changing sample2 doesn’t have any effect on sample1
  • We passed sample1 to the test function and then again changed its value in the test function at 0th index.  After that when we print sample1, we see that it hasn’t changed. The reason is same, when sample1 is passed as an argument to test function a copy of sample1 is created.

Different ways of iterating an array

An array can be iterated using:

  • Using for loop
  • Using for-range loop

Let’s see a code example for both

package main

import "fmt"

func main() {
    letters := [3]string{"a", "b", "c"}
    //Using for loop
    fmt.Println("Using for loop")
    len := len(letters)
    for i := 0; i < len; i++ {
        fmt.Println(letters[i])
    }
    //Using for-range operator
    fmt.Println("\nUsing for-range loop")
    for i, letter := range letters {
        fmt.Printf("%d %s\n", i, letter)
    }
}

Output

Using for loop
a
b
c

Using for-range loop
0 a
1 b
2 c

MultiDimensional Arrays

Below is the format for declaring a two dimensional array

sample := [x][y]{type}{{a11, a12 .. a1y},
                       {a21, a22 .. a2y},
                       {.. },
                       {ax1, ax2 .. axy}}     

where

  • x denotes the number of rows
  • y denotes the number of columns
  • aij denotes an element present at i row and j column

The same idea can be extended to three dimensions, four dimensions, and so on. All the rules we discussed above also apply to multidimensional arrays too.

Let's see a code example

package main

import "fmt"

func main() {
    sample := [2][3]int{{1, 2, 3}, {4, 5, 6}}
    fmt.Println("First Run")
    for _, row := range sample {
        for _, val := range row {
            fmt.Println(val)
        }
    }

    sample[0][0] = 6
    sample[1][2] = 1
    fmt.Println("\nSecond Run")
    for _, row := range sample {
        for _, val := range row {
            fmt.Println(val)
        }
    }
}

Output

First Run
1
2
3
4
5
6

Second Run
6
2
3
4
5
1

In above example we access the element of two dimensional array using index for both first and second dimension

sample[0][0] = 6

Also notice how we are traversing the two dimensional array. We need to use nested range . The first range traverses the arrays of array. The second range traverses the individual array after that.

Conclusion

This is all about array in Golang. Hope you have liked this article. Please share feedback/improvements/mistakes in comments.

Next Tutorial – Slice
Previous Tutorial – Struct

The post Understanding Array in Go (Golang) – Complete Guide appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/understanding-array-golang-complete-guide/feed/ 8 2137
Generate a random array/slice of n integers in Go (Golang) https://vikasboss.github.io/generate-random-array-slice-golang/ https://vikasboss.github.io/generate-random-array-slice-golang/#respond Thu, 02 Apr 2020 07:06:06 +0000 https://vikasboss.github.io/?p=1940 Overview math/rand package of GO provides a Perm method that can be used generate the pseudo-random slice of n integers. The array will be pseudo-random permutation of the integers in the range...

The post Generate a random array/slice of n integers in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

math/rand package of GO provides a Perm method that can be used generate the pseudo-random slice of n integers. The array will be pseudo-random permutation of the integers in the range [0,n).

To know more about what pseudo-random number means, checkout this post – https://vikasboss.github.io/generate-random-number-golang
Below is the signature of the function. It takes a number n as input and returns the permuted slice.

func Perm(n int) []int

Code:

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    //Provide seed
    rand.Seed(time.Now().Unix())

    //Generate a random array of length n
    fmt.Println(rand.Perm(10))
    fmt.Println(rand.Perm(10))
}

Output:

[6 0 1 5 9 4 2 3 7 8]
[9 8 5 0 3 4 6 7 2 1]

The post Generate a random array/slice of n integers in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/generate-random-array-slice-golang/feed/ 0 1940
Shuffle a slice or array in Go (Golang) https://vikasboss.github.io/shuffle-slice-or-array-go/ https://vikasboss.github.io/shuffle-slice-or-array-go/#respond Thu, 02 Apr 2020 06:53:18 +0000 https://vikasboss.github.io/?p=1928 Overview math/rand package of go provides a Shuffle method that can be used shuffle an array or a slice. This method pseudo-randomizes the order of elements using the default source. pseudo-randomizes means...

The post Shuffle a slice or array in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

math/rand package of go provides a Shuffle method that can be used shuffle an array or a slice. This method pseudo-randomizes the order of elements using the default source. pseudo-randomizes means that for a fixed input seed it will generate the same randomization. That is why in our program we will initialize the rand package with a different seed every time.

Below is the signature of the function.

func Shuffle(n int, swap func(i, j int))

This function takes in arguments

  • First is the length of the array or slice.
  • The second is a swap function that will be called for different indexes i and j. You need to provide your own swap function that will swap your elements in the array.

Also note that this function will panic if n<0. Let’s look at the code.

Code:

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed(time.Now().Unix())

    in := []int{2, 3, 5, 8}
    rand.Shuffle(len(in), func(i, j int) {
        in[i], in[j] = in[j], in[i]
    })
    fmt.Println(in)

    rand.Shuffle(len(in), func(i, j int) {
        in[i], in[j] = in[j], in[i]
    })
    fmt.Println(in)
}

Output:

It can produce a different output on your machine.

[5 3 2 8]
[3 5 8 2]

The post Shuffle a slice or array in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/shuffle-slice-or-array-go/feed/ 0 1928
Pick a random element in an array or slice in Go (Golang) https://vikasboss.github.io/pick-random-element-array-slice-go/ https://vikasboss.github.io/pick-random-element-array-slice-go/#respond Tue, 31 Mar 2020 15:55:50 +0000 https://vikasboss.github.io/?p=1912 Overview ‘mat/rand’ package of golang contains a Intn function that can be used to generate a pseudo-random number between [0,n). Bracket at the end means that n is exclusive. This function can...

The post Pick a random element in an array or slice in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

‘mat/rand’ package of golang contains a Intn function that can be used to generate a pseudo-random number between [0,n). Bracket at the end means that n is exclusive. This function can be utilized to pick a random element in an array or slice of int or string.

To know more about what pseudo-random number means, checkout this post – https://vikasboss.github.io/generate-random-number-golang

Below is the signature of this method. It takes input a number n and will return a number x in range 0<=x<n.

func Intn(n int) int

Code

We can directly index an element in a slice of int. See below program for picking up random from a slice of int.

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    in := []int{2, 5, 6}
    randomIndex := rand.Intn(len(in))
    pick := in[randomIndex]
    fmt.Println(pick)
}

Output:

Between 2, 5 or 6

The post Pick a random element in an array or slice in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/pick-random-element-array-slice-go/feed/ 0 1912
Sort a Custom Struct in Go (Golang) https://vikasboss.github.io/sort-custom-struct-collection-golang/ https://vikasboss.github.io/sort-custom-struct-collection-golang/#respond Fri, 27 Dec 2019 16:26:04 +0000 https://vikasboss.github.io/?p=1009 Introduction GO has a sort package that provides utility primitives for the sorting of slices and user-defined types. Any collection can be sorted by the Sort function of sort package of GO...

The post Sort a Custom Struct in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Introduction

GO has a sort package that provides utility primitives for the sorting of slices and user-defined types. Any collection can be sorted by the Sort function of sort package of GO it if implements the sort.Interface.

Below are the methods of sort.Interface

https://golang.org/pkg/sort/#Interface

type Interface interface {
    // Len is the number of elements in the collection.
    Len() int
    
    // Less reports whether the element with
    // index i should sort before the element with index j.
    Less(i, j int) bool
    
    // Swap swaps the elements with indexes i and j.
    Swap(i, j int)
}

Let’s see a working example to illustrate how we can use sort.Interface to sort a user-defined struct. In below example

  • We created a custom struct called employee with name and salary in dollars as fields
  • We have a employeeList which hold the list of employee.
  • employeeList implements the Len(), Less(), Swap() method hence it implements the sort.Interface
  • We sort the employee from highest salary to lowest salary. To sort employeeList we pass it to sort.Sort() function

Full Working Code:

package main

import (
    "fmt"
    "sort"
)

type employee struct {
    name   string
    salary int
}

type employeeList []employee

func (e employeeList) Len() int {
    return len(e)
}

func (e employeeList) Less(i, j int) bool {
    return e[i].salary > e[j].salary
}

func (e employeeList) Swap(i, j int) {
    e[i], e[j] = e[j], e[i]
}

func main() {
    eList := []employee{
        employee{name: "John", salary: 3000},
        employee{name: "Bill", salary: 4000},
        employee{name: "Sam", salary: 1000},
    }
    sort.Sort(employeeList(eList))
    for _, employee := range eList {
        fmt.Printf("Name: %s Salary %d\n", employee.name, employee.salary)
    }
}

Output:

Name: Bill Salary 4000
Name: John Salary 3000
Name: Sam Salary 1000

To sort from lowest salary to highest salary we need to change the Less function with ‘>’ sign

func (e employeeList) Less(i, j int) bool {
    return e[i].salary > e[j].salary
}

After changing it when we run the program then output will be:

Name: Sam Salary 1000
Name: John Salary 3000
Name: Bill Salary 4000

The post Sort a Custom Struct in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/sort-custom-struct-collection-golang/feed/ 0 1009
Go: Different ways of iterating over an Array and Slice https://vikasboss.github.io/go-different-ways-iterating-array-slice/ https://vikasboss.github.io/go-different-ways-iterating-array-slice/#respond Sun, 20 Oct 2019 07:20:42 +0000 https://vikasboss.github.io/?p=318 Go provides many different ways of iterating over an array. All examples below are also applicable to slice. Let’s define an array of letters first Using the range operator With index and...

The post Go: Different ways of iterating over an Array and Slice appeared first on Welcome To Golang By Example.

]]>
Go provides many different ways of iterating over an array. All examples below are also applicable to slice.

Let’s define an array of letters first

letters := []string{"a", "b", "c", "d", "e"}

Using the range operator

  • With index and value
for i, letter := range letters {
   fmt.Printf("%d %s\n", i, letter)
}
  • Only Value
for _, letter := range letters {
   fmt.Println(letter)
}
  • Only index
for i := range letters {
   fmt.Println(i)
}
  • Without value and index. Just print array values
i := 0
for range letters {
  fmt.Println(i)
  i++
}

Using Only For operator

  • Single initialization and post
len := len(letters)
for i := 0; i < len; i++ {
  fmt.Println(letters[i])
}
  • Multiple initialization and post statement
len := len(letters)
for i, j := 0, len; i < j; i, j = i+1, j-1 {
  fmt.Println(letters[i])
}

The post Go: Different ways of iterating over an Array and Slice appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/go-different-ways-iterating-array-slice/feed/ 0 318