Skip to content

Instantly share code, notes, and snippets.

@skplunkerin
Created October 21, 2020 21:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skplunkerin/8892d69c3faf7a62e324536e610539d4 to your computer and use it in GitHub Desktop.
Save skplunkerin/8892d69c3faf7a62e324536e610539d4 to your computer and use it in GitHub Desktop.
golang empty struct{} uses less memory, perfect for if exists ok checks

An empty struct struct{} uses 0 memory:

More on it here https://dave.cheney.net/2014/03/25/the-empty-struct.

It can be used with channels as well if you just want to notify whatever is listening on a channel that something happened and not to transfer data between goroutines.

// DO NOT DO THIS: (it uses more memory)
func removeDuplicateUsers(users []User) []User {
	u := map[string]bool{}
	cleanedUsers := []User{}
	for _, user := range users {
		if !u[user.ID] {
			u[user.ID] = true
			cleanedUsers = append(cleanedUsers, user)
		}
	}
	return cleanedUsers
}

// DO THIS INSTEAD:
func removeDuplicateUsers(users []User) []User {
	u := map[string]struct{}{}
	cleanedUsers := []User{}
	for _, user := range users {
		if _, ok := u[user.ID]; !ok { // check if already found/exists
			u[user.ID] = struct{}{}
			cleanedUsers = append(cleanedUsers, user)
		}
	}
	return cleanedUsers
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment