Brian Downs


Software Engineer, Open Source Advocate, Outdoor Enthusiast


Helpful Go Tips and Tricks

This is a collection of helpful tips and tricks I’ve come across in my time learning Go. I’ll continue to update this list with new things as I find them. Please feel free to use any of the examples, correct any mistakes, and make suggestions for additions.

Dedup an Array or Slice

Remove duplicate entries in an array or slice.

// []int{8, 6, 8, 2, 4, 4, 5, 9}
func Dedup1(l []int) []int {
	index := map[int]struct{}{}
	new := []int{}
	for _, v := range l {
		if _, ok := index[v]; !ok {
			index[v] = struct{}{}
			new = append(new, v)
		}
	}
	return new // [8 6 2 4 5 9]
}

Reverse the Order of an Array or Slice

Reverse the order of the elements in an array or a slice.

// []string{"a", "b", "c"}
func Reverse(s []string) []string {
	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
		s[i], s[j] = s[j], s[i]
	}
	return s // ["c", "b", "a"]
}

Map Operations

Convert a Map to url.Values object.

func ConvertToURLValues(data map[string]string) url.Values {
    v := url.Values{}
    for key, val := range data {
        v.Set(key, val)
    }
    return v
}