In Go, you can append to a slice while ensuring there are no duplicates by using a combination of checking if the element already exists before appending. One common approach is to use a helper function to check for the existence of an element, or to use a map for more efficient lookups.
Here’s an example where we append elements to a slice without duplicates using a helper function:
Method 1: Using a helper function to check for duplicates
package main
import (
“fmt”
)
// Helper function to check if an element is already in the slice
func contains(slice []int, element int) bool {
for _, v := range slice {
if v == element {
return true
}
}
return false
}
// Function to append without duplicates
func appendUnique(slice []int, elements …int) []int {
for _, elem := range elements {
if !contains(slice, elem) {
slice = append(slice, elem)
}
}
return slice
}
func main() {
slice := []int{1, 2, 3}
newElements := []int{3, 4, 5}
// Append elements without duplicates
result := appendUnique(slice, newElements…)
fmt.Println(result) // Output: [1 2 3 4 5]
}
Method 2: Using a map for more efficient lookups
If the slice gets large, a map can be used for O(1) lookups, which is more efficient than iterating through the slice:
package main
import (
“fmt”
)
// Function to append without duplicates using a map for faster lookup
func appendUnique(slice []int, elements …int) []int {
exists := make(map[int]bool)
// Add existing elements in slice to the map
for _, v := range slice {
exists[v] = true
}
// Append elements that are not already in the map
for _, elem := range elements {
if !exists[elem] {
slice = append(slice, elem)
exists[elem] = true
}
}
return slice
}
func main() {
slice := []int{1, 2, 3}
newElements := []int{3, 4, 5}
// Append elements without duplicates
result := appendUnique(slice, newElements…)
fmt.Println(result) // Output: [1 2 3 4 5]
}
Explanation:
- Method 1: The
containsfunction checks for duplicates by iterating through the slice. This is straightforward but can be inefficient for large slices. - Method 2: A map (
exists) is used to keep track of which elements have already been added to the slice. This allows for faster lookups (O(1)) and ensures no duplicates are added.
Both methods achieve appending without duplicates, but the map approach is more efficient for larger data sets.
