Home > Software design >  Is it possible to infer type parameters from what return values are assigned to?
Is it possible to infer type parameters from what return values are assigned to?

Time:05-11

Suppose I wrote two functions like this:

func ToInterfaceSlice[T any](s []T) []interface{} {
    res := make([]interface{}, len(s))
    for i, v := range s {
        res[i] = v
    }
    return res
}

func FromInterfaceSlice[T any](s []interface{}) (res []T, err error) {
    res = make([]T, len(s))
    for i, v := range s {
        vt, ok := v.(T)
        if !ok {
            return nil, fmt.Errorf("%v (type=%T) doesn't fit the target type %T", v, v, res)
        }
        res[i] = vt
    }
    return
}

When I parse type from the input parameters, I can simply use

    var m = []int{1, 2, 3}
    fmt.Println(ToInterfaceSlice(m))

The compiler knows the T is int.

However when I try passing type from the return variables

    var m []int
    m, _ = FromInterfaceSlice([]interface{}{1, 2, 3})
    fmt.Println(m)

The compiler gives error:

.\scratch.go:29:27: cannot infer T

I must explicitly pass the type in the function call:

    var m []int
    m, _ = FromInterfaceSlice[int]([]interface{}{1, 2, 3})
    fmt.Println(m)

Is there anything hard to infer type parameters from return type when the receiver vars are not interface? Or just not implemented, even not to implement on purpose?

Update #1 after the comment

I do know a, b := GenericFunc() cannot refer the type of returned value. Currently Go does have "it depends" case whether requires the explicit instantiation or not from the user input.

type Set[T comparable] map[T]struct{}

func NewSet[T comparable](eles ...T) Set[T] {
    s := make(Set[T])
    for _, ele := range eles {
        s[ele] = struct{}{}
    }
    return s
}

It's okay to use both t := NewSet(1, 2, 3) and t := NewSet[string](), but not var t NewSet[float64] = NewSet() now because of this

CodePudding user response:

The current rules for type inference are explicit. How the return values are used is not taken into account:

Type inference is based on

  • a type parameter list
  • a substitution map M initialized with the known type arguments, if any
  • a (possibly empty) list of ordinary function arguments (in case of a function call only)

As of Go 1.18 might simply rewrite your function to accept an argument of the required type; this has also the benefit of not hiding allocations inside the function body:

func FromInterfaceSlice[T any](s []interface{}, dst []T) error {
    if len(s) != len(dst) {
        return errors.New("lengths don't match")
    }
    for i, v := range s {
        vt, ok := v.(T)
        if !ok {
            return nil, fmt.Errorf("%v (type=%T) doesn't fit the target type %T", v, v, res)
        }
        dst[i] = vt
    }
    return nil
}

And pass in a destination slice with the required length:

func main() {
    src := []interface{}{1, 2, 3}
    m := make([]int, len(src))
    _ = FromInterfaceSlice(src, m)
    fmt.Println(m)
}

If you can't or don't want to determine the slice's length beforehand, you are left with explicit instantiation.


Also the type parameters are still not inferrable with := shorthand declaration:

// what is m???
m, err := FromInterfaceSlice([]interface{}{1, 2, 3})
  • Related