Skip to content

Golang Slices and operations

package main

import "fmt"

func main() {

    xArr := [4]string{"Welcome to the jungle", "Jumanji is your friend", "Something to remind you", "System of a down"}

    fmt.Println(len(xArr))

    fmt.Printf("Type of Var %T\n", xArr)
    for _, elem := range xArr {

        if len(elem) == 0 {
            fmt.Printf("Length Of Element is 0. Array element empty")
        } else {
            fmt.Printf("Element in Array %v\t:", elem)
            fmt.Printf("Lenght of Array Elem %d\n", len(elem))
        }

    }
    fmt.Println("==============================")
    fmt.Println("==============================")
    xNewElem := "Nothing Else Maters"
    // Add elements to Slice Append
    newArray := append(xArr[:], xNewElem)
    fmt.Println(newArray)
    fmt.Println(len(newArray))
    fmt.Println("==============================")
    fmt.Println("==============================")
    // To append element to an Array you need to convert it to slice with '[:]' array[:]
    convertArray := [5]int{1, 2, 3, 4, 5}
    fmt.Printf("Type of Element %T\n", convertArray)
    newconvertArray := convertArray[:]
    fmt.Printf("Type of Element %T\n", newconvertArray)
    // Print values of a slice
    for i := 0; i < len(xArr); i++ {
        fmt.Printf("Vlaues of the Slice without range loop Index: %v \t Value: %v\n", i, xArr[i])
    }
    fmt.Println("==============================")
    fmt.Println("==============================")
    // Append slice to slice . New Song slice metallica
    newSongListMetal := []string{
        "One",
        "Creeping Death",
        "Fuel",
        "War Pigs",
        "Paranoid",
        "Blackened",
        "Battery",
        "Hallowed Be Thy Name",
        "Painkiller",
        "Overkill",
        "Roots Bloody Roots",
        "Walk",
        "Cowboys From Hell",
        "Holy Diver",
        "Ace of Spades",
        "The Trooper",
        "Toxicity",
        "Chop Suey",
        "Duality",
        "Raining Blood",
    }
    newSongList := append(newArray, newSongListMetal...)
    for i := 0; i < len(newSongList); i++ {
        fmt.Printf("Vlaues of the Slice without range loop Song Index: %v \t Song: %v\n", i, newSongList[i])
    }
    fmt.Println("==============================")
    fmt.Println("==============================")
    // slicing a slice element 2 to 15
    // Potentially creating new slice with the sliced values
    slicedElement := newSongList[2:15]
    fmt.Printf("Sliced Value %v\n",slicedElement)
    fmt.Println("==============================")
    fmt.Println("==============================")
    // Deleting from a slice. We gonna use the append and delete
    // Deleting last element 19 Song Raining Blood , using slice... to expand the slice into elements and append them 
    // Slicing method 19 element to 20th element -> newSongListMetal[:19], newSongListMetal[20:]...
    fmt.Println("Slice Before Deletion")
    for i := 0; i < len(newSongListMetal); i++ {
        fmt.Printf("Index %d \tSlice new Elements after deltion %v\n",i,newSongListMetal[i])
    }
    fmt.Println("==============================")
    fmt.Println("==============================")
    fmt.Println("SLice After Deletion")
    fmt.Println("==============================")
    fmt.Println("==============================")
    newSongListMetal = append(newSongListMetal[:19], newSongListMetal[20:]...)
    for i := 0; i < len(newSongListMetal); i++ {
        fmt.Printf("Index %d \tSlice new Elements after deltion %v\n",i,newSongListMetal[i])
    }
    fmt.Println("==============================")
    fmt.Println("==============================")
}

Sorting slices and structs.

type Person struct {
    First string
    Age   int
}

type ByAge []Person // we create a ByAge slice of type Person 
  • By Age.

    func (a ByAge) Len() int           { return len(a) }
    func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
    func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
    
  • By Name

    func (bn ByName) Len() int           { return len(bn) }
    func (bn ByName) Swap(i, j int)      { bn[i], bn[j] = bn[j], bn[i] }
    func (bn ByName) Less(i, j int) bool { return bn[i].First < bn[j].First }
    
func main() {
    p1 := Person{"James", 32}
    p2 := Person{"Moneypenny", 27}
    p3 := Person{"Q", 64}
    p4 := Person{"M", 56}

    people := []Person{p1, p2, p3, p4}

    fmt.Println(people)
    sort.Sort(ByName(people))
    fmt.Println(people)
}

Bitwise Operators

Operator Type Description
^x Unary Bitwise NOT (invert bits)
x ^ y Binary Bitwise XOR
& Binary Bitwise AND
| Binary
&^ Binary AND NOT (clear bits)
<< Binary Shift left
>> Binary Shift right