Sobes.tech
Middle+

Live coding: how to deduplicate addresses in a list to call unique addresses using map.

sobes.tech AI

Answer from AI

For deduplication of an address list in Go, it is convenient to use a map where the key is the address, and the value is a boolean or an empty struct for memory efficiency.

Example:

package main

import "fmt"

func uniqueAddresses(addresses []string) []string {
    seen := make(map[string]struct{})
    var result []string

    for _, addr := range addresses {
        if _, exists := seen[addr]; !exists {
            seen[addr] = struct{}{}
            result = append(result, addr)
        }
    }
    return result
}

func main() {
    addresses := []string{"addr1", "addr2", "addr1", "addr3", "addr2"}
    unique := uniqueAddresses(addresses)
    fmt.Println(unique) // Output: [addr1 addr2 addr3]
}

Here, map[string]struct{} is used for efficient storage of unique keys without additional memory consumption for values. The resulting slice contains only unique addresses, allowing them to be called once.