Collections in Go

go library provides built-in collection types to handle different data structures.

Arrays

An array in Go is a fixed-size collection of elements of the same type. Once you define the size of an array, it cannot be changed

func main() {
    arr := [6]int{1,2,3,4,5,6}    //[n values] type {}
    var len = len(arr);
}
        

Channels

Communication and synchronization between goroutines=Tasks in Rust (concurrently executing functions). They provide a way to send and receive data safely between goroutines

Slices [] (Dynamic Array) = C++(vector<int>) = Rust(vec<i32>)

A slice represents a view of contiguous sequence of elements in memory
Slice contains 3 components:
1. Pointer to underlying array: A slice holds a reference to the underlying array that stores the elements.
2. Length: number of elements in slice.
3. Capacity: maximum number of elements it can hold
Declaration

var arr []int                       //Empty vector
slice := make([]int, 5)             //Slice size=5
        
Initilization

arr := []int {1,2,3,4,5,6}        //Length=6. number of elements provided
for i:=0; i<5; i++ {
    slice[i] = 0;
}
        
Modification
Changing elements of a slice modifies the corresponding elements of its underlying array
        
slc[0] = 899
fmt.Println(arr[1])             //899
        
Length, Capacity
         
// length: no of elements slice contains
// capacity: no of elements in underlying array
    fmt.Println(len(slc),cap(slc))  //3 5
        
Nil Slice

var nilSlc[]int
fmt.Println(len(nilSlc), cap(nilSlc))   //0 0
        
ReSlice
        
//Slice the Slice's length to new length
slc1 := []int{10,20,30,40,50}
slc1 = slc1[:0]
fmt.Println(slc1)                       //[]
slc1 = slc1[:4]
fmt.Println(slc1)                       //[10,20,30,40]
slc1 = slc1[2:]
fmt.Println(slc1)                       //[30,40]
        
Make Slice
          
// make() allocates a zeroed array and returns a slice that refers to that array
slc2 :=make([]int, 5)                   //[0 0 0 0 0]
fmt.Println(slc2)
        
Append
 
//append(slice, element). Append new element to slice
slc3 := []int{10,20,30,40,50}           //[10 20 30 40 50 60]
slc3 = append(slc3,60)
fmt.Println(slc3)    
        
Sort
 
v := []int
sort.Ints(v)

// sort [][]
v = :[][]
sort.Slice(v, func(i, j int) bool {
    return v[i][0] < v[j][0]
})
        
2D vector

// Method-1: Declare a 2D vector
var test [][]int     

// Method-2: Declare an empty 2D vector
test := make([][]int, rows)
// Initialize each row with specific length
for i := range vector {
    test[i] = make([]int, cols)
}

// Method-3: Declare an empty 2D vector
var test [][]int
// Initialize each row with specific length
for i := 0; i < rows; i++ {
    test = append(test, make([]int, cols))
}


// Initialize the 2D vector with values
test = [][]int {
    1,2,3
    4,5,6
}

// Accessing elements in the 2D vector
fmt.Println(vector[0][0]) // Output: 1
        

Queue(Implemented using slice)


package main
import "fmt"
type test struct {		//Declare a struct having slice which will act as queue
    q []int
}
func Constructor() test {
    return test{}
}
func (this *test) Push(x int)  {
    this.q = append(this.q, x)		//Push() append x to queue
}
func (this *MyStack) Pop() {
    this.q = this.q[1:]   		//Pop() Remove 1st element
}
func (this *MyStack) Top() int {
    return this.q[0]			//Top()
}
func (this *MyStack) Empty() bool {	//Size()
    if len(this.q) == 0 {
        return true
    }
    return false
}
        

Stack using slice

(struct = class)

Class is defined as struct type. Example: Person is defined of type struct.
The struct type can be considered similar to a class, as it allows you to define fields and associated methods.

package main
import "fmt"

type student struct {		// Define a struct type
    name string
    age  int
    marks []int		// slice = dynamic ints
    misc []interface{}	// misc is a slice that can hold values of any type
}

// Define a method associated with the Person struct
// To associate a method with a struct, define a method with a receiver type that matches the struct type.
func (p Person) SayHello() {
    fmt.Printf("Hello, my name is %s and I am %d years old.\n", p.name, p.age)
}

func main() {
    // Create a new instance of Person
    person := Person{name: "John", age: 30}

    // Call the SayHello method
    person.SayHello()
}
        

Linked List