Generics - type inference - which type parameters?

137 views
Skip to first unread message

Patrick Smith

unread,
Aug 24, 2020, 7:34:46 PM8/24/20
to golang-nuts
I may be missing something, but it seems to me that one point in the draft's discussion of type inference could usefully be clarified (https://go.googlesource.com/proposal/+/refs/heads/master/design/go2draft-type-parameters.md#type-inference).

The term "type parameter" there should be restricted to the type parameters in the specific use of a generic type or function for which we are trying to infer type arguments. For example (https://go2goplay.golang.org/p/pWis3rlJElu)

func Min[type T interface{ type int, uint }](a, b T) T {
if b < a {
return b
}
return a
}

func Min3[type U interface{ type int }](a, b, c U) U {
return Min(a, Min(b, c))
}

func BadMin3[type V interface{ type int, uint, string }](a, b, c V) V {
return Min(a, Min(b, c))
}

Here, U and V are type parameters, but when inferring type arguments for the calls to Min, we must consider U and V as fixed types, not subject to type unification. This seems needed in order for the compiler to reject BadMin3.

Ian Lance Taylor

unread,
Aug 24, 2020, 7:47:27 PM8/24/20
to Patrick Smith, golang-nuts
Thanks. That seems fairly clear to me, but I'm probably too close to
the problem. Any suggestions for exactly where we should add a
sentence, and what that sentence should be? Thanks.

Ian

Patrick Smith

unread,
Aug 24, 2020, 8:49:50 PM8/24/20
to Ian Lance Taylor, golang-nuts
Perhaps near the end of the type inference section, before "Note: type inference is a convenience feature"? And perhaps something like this?

When discussing type inference, the term "type parameter" refers only to the type parameters in a specific use of a generic function or type. For example,

func Min[T interface{ type int, uint }](a, b T) T {

    if b < a {
        return b
    }
    return a
}

func Min3[U interface{ type int }](a, b, c U) U {
    return Min(a, Min(b, c))
}

While inferring the type argument for the calls to Min, T is considered a type parameter, but U is considered to be a fixed type, not subject to type unification.
Reply all
Reply to author
Forward
0 new messages