Monday, 13 May 2019

Go language: Check for equality of slices


By looping over the elements of slices, you can check whether slices are equal or not.

Procedure looks like below.
a.   If both the slices are nil, then return true
b.   If only one of the slice is nil, then return false
c.    If length of slices is not equal, then return false.
d.   Iterate over the elements of slices and return false, if any element is not matches

func IsSlicesEqual(slice1 []string, slice2 []string) bool {
    if slice1 == nil && slice2 == nil {
        return true
    }

    if slice1 == nil {
        return false
    }

    if slice2 == nil {
        return false
    }

    if len(slice1) != len(slice2) {
        return false
    }

    for index, value := range slice1 {
        if value != slice2[index] {
            return false
        }
    }

    return true
}

App.go
package main

import "fmt"

//IsSlicesEqual return true if the slices have same elements else false
func IsSlicesEqual(slice1 []string, slice2 []string) bool {
    if slice1 == nil && slice2 == nil {
        return true
    }

    if slice1 == nil {
        return false
    }

    if slice2 == nil {
        return false
    }

    if len(slice1) != len(slice2) {
        return false
    }

    for index, value := range slice1 {
        if value != slice2[index] {
            return false
        }
    }

    return true
}

func main() {
    slice1 := []string{"Krishna", "Ram", "Chamu"}
    slice2 := []string{"Krishna", "Ram", "Sowmya"}
    slice3 := []string{"Krishna", "Ram", "Chamu"}

    fmt.Printf("%v == %v : %v\n", slice1, slice2, IsSlicesEqual(slice1, slice2))
    fmt.Printf("%v == %v : %v\n", slice1, slice3, IsSlicesEqual(slice1, slice3))
    fmt.Printf("%v == %v : %v\n", slice2, slice3, IsSlicesEqual(slice2, slice3))
}


Output
[Krishna Ram Chamu] == [Krishna Ram Sowmya] : false
[Krishna Ram Chamu] == [Krishna Ram Chamu] : true
[Krishna Ram Sowmya] == [Krishna Ram Chamu] : false

Approach 2: Using reflect.DeepEqual()
reflect.DeepEqual(slice1, slice2)


App.go
package main

import (
    "fmt"
    "reflect"
)

func main() {
    slice1 := []string{"Krishna", "Ram", "Chamu"}
    slice2 := []string{"Krishna", "Ram", "Sowmya"}
    slice3 := []string{"Krishna", "Ram", "Chamu"}

    fmt.Printf("%v == %v : %v\n", slice1, slice2, reflect.DeepEqual(slice1, slice2))
    fmt.Printf("%v == %v : %v\n", slice1, slice3, reflect.DeepEqual(slice1, slice3))
    fmt.Printf("%v == %v : %v\n", slice2, slice3, reflect.DeepEqual(slice2, slice3))
}

Output
[Krishna Ram Chamu] == [Krishna Ram Sowmya] : false
[Krishna Ram Chamu] == [Krishna Ram Chamu] : true
[Krishna Ram Sowmya] == [Krishna Ram Chamu] : false




Previous                                                 Next                                                 Home

No comments:

Post a Comment