DEV Community

Chanchal Verma
Chanchal Verma

Posted on

Data structure in Golang

Golang has gained tremendous popularity in software development in few years of its launch since it was made available to public.

I'm not intending to share here the full history of language, but go to the very few basic topics Here:

The basic data structures of Golang include:

  1. Array
  2. Slice
  3. Map
  4. Struct
  • Methods

  • Interfaces

1. Array
This data structures is used to stored fixed number of elements. So once an array is defined, elements cannot be added or removed from the array. Note that, we can set the value for any of the index in the array.

Way to define the array :

var arr [size]type //general syntax
Enter fullscreen mode Exit fullscreen mode

Examples:

var arrInteger [5]int //integer type array with five elements
var arrString  [5]string //string type array with five element
Enter fullscreen mode Exit fullscreen mode

Defining array with predefined elements:

a:=[5]int{1,2,3,4,5}//defining and populating array
b:=[5]string{"first","second","third","fourth","fifth"}
Enter fullscreen mode Exit fullscreen mode

:= This is short declaration operator

2. Slice
Slice gives a more robust interface to sequences compared to array. Unlike an array, no need to specify the length of the slice when defining it.

Way to declare or define slice

var slice_name []type //general syntax
Enter fullscreen mode Exit fullscreen mode
Three way to create slice:

var s []int //integer type 

s:=[]{1,2,3,4,5} // slice with elements and short notation

s:=make([]int,n) // n is the number of the elements
Enter fullscreen mode Exit fullscreen mode

3. Map
It is possible for you to use key value pairs to refer an element. This is accomplish using map. If you coming from JavaScript, php background, see map as your object.

General syntax of Map:

map[keyType]valueType
Enter fullscreen mode Exit fullscreen mode

Way to define Map:

var sampleMap=map[string]int //using var

sampleMap:=map[string]int // shorthand notation

sampleMap:=make(map[string]int)//using make()
Enter fullscreen mode Exit fullscreen mode

4. Struct
Go struct is a collection of named fields/properties. A struct can have the same or different types of fields.

Way to define struct

type person struct{
firstName string
lastName  string
age       int
}
Enter fullscreen mode Exit fullscreen mode

Methods
A method in Go is a function is a function that is associated with a specific type. This allows the function to operate on instances of that type, enabling behavior similar to object-oriented programming.

Interfaces
Interfaces in Go is a type that specifies a set of method signatures. A type implements an interface by providing definitions for all the methods declared by the interface. Interfaces are a powerful way to define and work with abstractions.

Top comments (0)