Original post

I’m a long-time PHP developer looking to pick up . As part of the learning process, I’m practicing writing some basic algorithms so I can get used to the syntax, packages, etc. I was quite surprised to learn that so many built-in functions in PHP don’t exist in ; which I suppose is because of the strict typing.

For example, calculating symmetric difference: https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/find-the-symmetric-difference

In PHP:

function sym() {
  $results = [];
  foreach (func_get_args() as $arg) {
    $arg = array_unique($arg);
    $results = array_merge(array_diff($results, $arg), array_diff($arg, $results));
  }
  sort($results);
  return $results;
}

In Go (my attempt, given very limited experience):

func sym(lists ...[]int) []int {
        if len(lists) < 2 {
                panic("Lists must contain 2 or more lists.")
        }

        diff := []int{}
        for _, list := range lists {
                list = arrayUnique(list)
                diff = append(arrayDiff(diff, list), arrayDiff(list, diff)...)
        }

        sort.Ints(diff)

        return diff
}

func arrayUnique(arr []int) []int {
        m := make(map[int]struct{})

        for _, val := range arr {
                m[val] = struct{}{}
        }

        values := make([]int, 0, len(m))
        for k := range m {
                values = append(values, k)
        }

        return values
}

func arrayDiff(arr1, arr2 []int) []int {
        m := make(map[int]struct{})

        var diff []int

        for _, val := range arr1 {
                m[val] = struct{}{}
        }

        for _, val := range arr2 {
                if _, ok := m[val]; !ok {
                        diff = append(diff, val)
                }
        }

        return diff
}

I suppose my questions are:

  1. Does what I wrote in Go look correct for this?

  2. Is it normal that it takes this much code to do something quite simple?

  3. Why is all of this required rather than the language providing utility functions (I assuming typing)?

  4. On large projects, do developers tend to provide a library of useful helpers like these?