Skip to content

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
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.

2 participants