Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider a generic implementation of Unique() func #175

Open
ilmanzo opened this issue Oct 1, 2024 · 2 comments
Open

Consider a generic implementation of Unique() func #175

ilmanzo opened this issue Oct 1, 2024 · 2 comments

Comments

@ilmanzo
Copy link
Contributor

ilmanzo commented Oct 1, 2024

with reference to:

func unique(a []int) []int {

and

func unique64(a []int64) []int64 {

a sample implementation with generics types (introduced in Go 1.18) that also avoids allocating a map of bools:

func unique[T comparable](slice []T) []T {
    seen := make(map[T]struct{})
    unique := []T{}

    for _, item := range slice {
        if _, exists := seen[item]; !exists {
            seen[item] = struct{}{}
            unique = append(unique, item)
        }
    }

    return unique
}

to call it:

uniqueInts := unique([]int{1, 2, 2, 3, 4, 4, 5})
uniqueStrings := unique([]string{"apple", "banana", "apple", "cherry"})
uniqueFloat64s := unique([]float64{1.1, 2.2, 2.2, 3.3, 4.4})
@ilmanzo
Copy link
Contributor Author

ilmanzo commented Oct 1, 2024

Opening this issue only to have your opinion, if you like the idea I will follow up with a Pull Request :)

@grisu48
Copy link
Collaborator

grisu48 commented Oct 3, 2024

This would be a great refactoring idea. I think the code still originates from the pre-generics time, or at least when we used a go version that didn't had generics.

Feel free to open a PR 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants