Data Structure In Golang 2020

Check This Previous blog post written by Sagar Jaybhay for better understanding.

In this article, i will explain Data Structure In Golang. With In detail explanation of Array, Slice, Maps in golang.

It is for how you store data. There are different forms of data-storage mechanism means we save data using variable name means that the variable holds our data. Like this way,

We have an array, slice, map and struct types of data structure we use in our golang.

Array in Golang

It is a data structure consist of elements.

  • Each element is identified by an index of an array element.
  • It of fixed size.
  • The index is 0 based means index start with 0.
  • I­f we want to declare an array we need to give a size for an array.
  • It is a numbered sequence of elements of a single type.
  • The number of an element is an array is the length of an array and it is non-negative.
  • The length is part of array type so we can’t change the size of an array.

package main

import "fmt"

func main() {

    var x [10]int

    fmt.Println("Printing array : ", x)

    fmt.Println("array length : ", len(x))

    fmt.Println("x[4] value is  : ", x[4])

    for i:= 0; i < 10; i++ {
        x[i] = 100 + i*20
    }
    fmt.Println("printing added value array :")
    fmt.Println(x)

}

In the above program, we use var for declaring an array. So we use var that’s why it initializes that array to 0 value.

array in golang
array in golang

Slice In Golang

In golang slice is a more flexible and mostly used data structure. In golang or any language, an array is a fixed size and on the other hand, a slice is dynamically sized. In golang, it is a commonly used data structure.

Slice is more convenient than the array. Slice is a lightweight data structure. In slice like array you need to store the same types of elements, you can’t store different types of elements in the array. Slice is similar to an array that having index value and length but the slice is dynamically growing or shrink it is more kind of list in other languages like C#, Java. Slice is declared like an array but size doesn’t mention.

Points to remember:

  1. The value of uninitialized slice is nil.
  2. It is a reference type.
  3. When we initialize slice is always associated with an underlying array that holds its elements.
  4. A slice formed by specifying 2 indices a high bound and low bound which is separated by a colon.
  5. A bracket without size is a slice.

A[low:high]

A[1,4]

package main

import "fmt"

func main() {
    primes:= [6]int{2, 3, 5, 7, 11, 13}

    //fmt.Printf("%v %T", primes)
    fmt.Println("Printing complete slice", primes)
    var s []int = primes[1:4] // this is slicing the slice
    fmt.Println(primes[2])    //index access ; access by index

    fmt.Println(s)
}

slice in golang
slice in golang

Code for appending the slice

package main

import "fmt"

func main() {

    /*
            primes := [6]int{2, 3, 5, 7, 11, 13}
            fmt.Printf("%v %T", primes)
            fmt.Println("Printing complete slice", primes)
            var s []int = primes[1:4] // this is slicing the slice
            fmt.Println(primes[2])    //index access ; access by index
            fmt.Println(s)

        var myslice []string
        fmt.Print(myslice)
        fmt.Printf()
    */
    //------------------ appending elements to slice beyond it capacity -----------------------------
    myslice := make([]string, 3, 5)
    // 3 is length:- it is number of elements refered by slice
    // 5 is capacity:- it is number of elements in underlying array.

    myslice[0] = "Sagar"
    myslice[1] = "Jaybhay"
    myslice[2] = "Sr. Software Developer"

    fmt.Println(myslice)
    fmt.Println("Orignal Length ", len(myslice))
    fmt.Println("Orignal Capcity ", cap(myslice))

    myslice = append(myslice, "Pune")
    myslice = append(myslice, "Maharashtra")
    myslice = append(myslice, "India")

    fmt.Println("Updated ", myslice)
    fmt.Println("Updated Length ", len(myslice))
    fmt.Println("Updated Capcity ", cap(myslice))

}

appending to slice
appending to slice

How to create a multidimensional slice?

In the below code, we are creating a multi-dimensional slice.

records := make([][]string, 2)

    emp := make([]string, 2)
    emp[0] = "A"
    emp[1] = "B"

    records = append(records, emp)
    fmt.Println("first array appended")
    fmt.Println(records)

    emp1 := make([]string, 2)
    emp1[0] = "A"
    emp1[1] = "B"

    records = append(records, emp1)

    fmt.Println("Second array appended")
    fmt.Println(records)

multidimentinal slice in golang
multidimentinal slice in golang

What are different ways to declare a slice?

Shorthand method:  when you declared a slice with shorthand syntax it will create an underlying array and it not nil.

record:= []string{}

    fmt.Println(record)        //o/p = []
    fmt.Println(record == nil) // o/p  = false

Declare using var: by using var there is no underlying array is created and it is nil.

var record []string
    fmt.Println(record)        //o/p = []
    fmt.Println(record == nil) // o/p  = true

Using make: by using make you can create slice need to give length or capacity.

record:= make([]string, 20)
    fmt.Println(record)        //o/p = []
    fmt.Println(record == nil) // o/p  = false

Maps In Go Language

  1. Map is another data structure in golang for storing data.
  2. Map is a key-value association and it like our dictionary in C# and uses the key to identify the value in the map.
  3. Remember map is key/ value storage
  4. Map is built on a hash table as an underlying data structure.
  5. The value of an uninitialized map is nil.
  6. Map is a reference type like a slice.

package main

import "fmt"

func main() {

    m := make(map[string]int) // create map here
    m["k1"] = 7
    m["k2"] = 10

    fmt.Println(m)

}

maps in golang
maps in golang

To add elements in a map you need to provide key and value for that key.

m := make(map[string]int) // create map here
    m["k1"] = 7

in above code we created map “m “ and at ” k1” key assign value 7 so to give value you need to use this m[“key”]=value

To delete elements from the map you need to use delete function and that function will take the first parameter is map name and the second parameter is key in that map.

m := make(map[string]int) // create map here
    m["k1"] = 7
    m["k2"] = 10

    fmt.Println(m) //map[k1:7 k2:10]

    delete(m, "k1")

complete program is

package main

import "fmt"

func main() {

    m := make(map[string]int) // create map here
    m["k1"] = 7
    m["k2"] = 10

    fmt.Println(m) //map[k1:7 k2:10]

    delete(m, "k1")
    fmt.Println(m) //map[k2:10]

    pt, kt := m["k2"]

    fmt.Println(pt, kt) //10 true

}

GitHub Project Link :- https://github.com/Sagar-Jaybhay/GoLanguageLab

Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer at Software Company. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

Sagar Jaybhay

Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer at Software Company. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

You may also like...