golang diff of string arrays

To find the difference between two string arrays in Go (Golang), you can follow these steps:

  1. Declare two string arrays: Start by declaring two string arrays, let's call them array1 and array2.

  2. Initialize the arrays: Assign values to the arrays by specifying the elements within curly brackets. For example, array1 := []string{"apple", "banana", "orange"} and array2 := []string{"banana", "grape", "orange"}.

  3. Create a map: Initialize an empty map, let's call it diffMap, to store the differences between the arrays. The map will have the string element as the key and a boolean value to indicate whether the element is present in both arrays or not.

  4. Iterate over array1: Use a for loop to iterate through each element in array1. For each element, check if it exists in array2 using a for loop and an if statement.

  5. Add elements to the map: If the element is not present in array2, add it to the diffMap with a value of true.

  6. Iterate over array2: Repeat the same process as step 4, but this time iterate over array2 and check if each element exists in array1.

  7. Add elements to the map: If the element is not present in array1, add it to the diffMap with a value of false.

  8. Print the differences: Iterate over the diffMap and print the elements that have a value of true, indicating that they are present in array1 but not in array2.

Here is an example code snippet that demonstrates the above steps:

package main

import "fmt"

func main() {
    array1 := []string{"apple", "banana", "orange"}
    array2 := []string{"banana", "grape", "orange"}

    diffMap := make(map[string]bool)

    for _, element := range array1 {
        found := false
        for _, value := range array2 {
            if element == value {
                found = true
                break
            }
        }
        if !found {
            diffMap[element] = true
        }
    }

    for _, element := range array2 {
        found := false
        for _, value := range array1 {
            if element == value {
                found = true
                break
            }
        }
        if !found {
            diffMap[element] = false
        }
    }

    for element, isPresentInArray1 := range diffMap {
        if isPresentInArray1 {
            fmt.Println(element, "is present in array1 but not in array2.")
        } else {
            fmt.Println(element, "is present in array2 but not in array1.")
        }
    }
}

This code will output:

apple is present in array1 but not in array2.
grape is present in array2 but not in array1.

Please note that the code assumes that the elements in the arrays are unique. If there are duplicate elements, the code will only consider the first occurrence of each element.