Let's consider the following situation:

I have generic function which can accepts function arguments defined as 
any. Now if want to know exactly the type of function arguments I have to 
use the reflect package. The problem is that although on function 
invocation we can explicitly define the type constraints, these are not 
taken into consideration when we are matching the concrete types using the 
reflect type switch.

So let's say, that I have the following function:

// Flatten flattens the slice all the way to the deepest nesting level.
func Flatten[T any](slice any) ([]T, error) {
        return baseFlatten([]T{}, slice)
}

func baseFlatten[T any](acc []T, slice any) ([]T, error) {
        var err error

        switch v := any(slice).(type) {
        case T:
                acc = append(acc, v)
        case []T:
                acc = append(acc, v...)
        case []any:
                for _, sv := range v {
                        acc, err = baseFlatten(acc, sv)
                        if err != nil {
                                return nil, errors.New("flattening error")
                        }
                }
        default:
                return nil, errors.New("flattening error")
        }

        return acc, nil
}

I would expect that calling the Flatten method in the following way, the 
types to be inferred correctly and the input values to be recognized as 
float32 and NOT float64. Because otherwise I don't see the reason to use an 
explicit type constraint on function invocation.  

input := []any{[]float32{1.0, 2.0}, 1.1}
result, err := Flatten[float32](input)

The generic type switch cases as defined in the proposal (
https://go.googlesource.com/proposal/+/HEAD/design/43651-type-parameters.md#generic-types-as-type-switch-cases)
 
is not intuitive, at least for me.   

Now the question is how could I infer correctly the parameter type without 
explicitly defining the value 1.1 as float32 like this:

input := []any{[]float32{1.0, 2.0}, float32(1.1)}
result, err := Flatten[float32](input)

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/9cd2161f-da81-4bcf-9c69-442259d8d2ebn%40googlegroups.com.

Reply via email to