AllenDang / giu

Cross platform rapid GUI framework for golang based on Dear ImGui.
MIT License
2.28k stars 133 forks source link

feat: use generics for RangeBuilder #824

Closed zenlor closed 2 months ago

zenlor commented 2 months ago

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