To remove duplicates from an array in Go, you can use a map or a loop to filter out duplicate elements.
In this example,
package main
import (
"fmt"
)
func main() {
numbers := []int{1, 2, 2, 3, 4, 4, 5}
uniqueNumbers := make(map[int]bool)
result := []int{}
for _, num := range numbers {
if !uniqueNumbers[num] {
result = append(result, num)
uniqueNumbers[num] = true
}
}
fmt.Println("Array without duplicates:", result)
}
Array without duplicates: [1 2 3 4 5]
In this example,
package main
import (
"fmt"
)
func main() {
colors := []string{"red", "green", "blue", "green", "yellow", "blue"}
uniqueColors := []string{}
for _, color := range colors {
found := false
for _, uc := range uniqueColors {
if color == uc {
found = true
break
}
}
if !found {
uniqueColors = append(uniqueColors, color)
}
}
fmt.Println("Array without duplicates:", uniqueColors)
}
Array without duplicates: [red green blue yellow]
In this tutorial, we learned How to Remove Duplicates in an Array in Go language with well detailed examples.