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

feat: use generics for RangeBuilder #824

Merged
merged 1 commit into from
Jul 13, 2024

Conversation

zenlor
Copy link
Contributor

@zenlor zenlor commented Jul 12, 2024

Very small PR to use generics instead of any as type for the slices passed to RangeBuilder

The reason this is useful is because []any forces the type to be an interface and a, for example, string slice []string{} can't be cast to []interface{} due to how slices work in Go.

Example:

package main

import "fmt"

func rangeOver(values []any, do func(i int, data any)) {
        for i, v := range values {
                do(i, v)
        }
}

func rangeOverG[S ~[]T, T any](values S, do func(i int, data T)) {
        for i, v := range values {
                do(i, v)
        }
}

func main() {
        data := []string{"one", "two"}
        ranger := func(i int, item string) {
                fmt.Println(i, item)
        }
        rangeOver(data, ranger)
        rangeOverG(data, ranger)
}

Go compile error:

./main.go:22:12: cannot use data (variable of type []string) as []any value in argument to rangeOver
./main.go:22:18: cannot use ranger (variable of type func(i int, item string)) as func(i int, data any) value in argument to rangeOver

When using the rangeOverG function the user of the function can pass any data type provided the receiving function has the right signature

Copy link
Collaborator

@gucio321 gucio321 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lgtm, thank you

@gucio321 gucio321 merged commit 307d04f into AllenDang:master Jul 13, 2024
4 checks passed
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

Successfully merging this pull request may close these issues.

None yet

2 participants