配列のdiff取得

main.go

package main

import "log"

func main() {
    array1 := []string{"1", "2"}
    array2 := []string{"2", "3"}
    d := diffArray(array1, array2)
    log.Print(d.Add)
    log.Print(d.Delete)
}

type diff struct {
    Add    []string
    Delete []string
}

func diffArray(baseArray, compareArray []string) *diff {
    var d diff
    for _, b := range baseArray {
        if !findStr(compareArray, b) {
            d.Delete = append(d.Delete, b)
        }
    }
    for _, c := range compareArray {
        if !findStr(baseArray, c) {
            d.Add = append(d.Add, c)
        }
    }
    return &d
}

func findStr(args []string, str string) bool {
    for _, v := range args {
        if v == str {
            return true
        }
    }
    return false
}

テストコード

package main

import (
    "testing"
)

func TestFindStr(t *testing.T) {
    if !findStr([]string{"1", "2"}, "1") {
        t.Error()
    }
}

func TestDiffArray(t *testing.T) {
    d := diffArray([]string{"1", "2"}, []string{"2", "3", "4"})
    if d.Add[0] != "3" {
        t.Error()
    }
    if d.Add[1] != "4" {
        t.Error()
    }
    if d.Delete[0] != "1" {
        t.Error()
    }
}