The current proposal says
<https://go.googlesource.com/proposal/+/refs/heads/master/design/go2draft-type-parameters.md#using-types-that-refer-to-themselves-in-constraints>
*The rule is that if a type contraint has a single type parameter, and it
is used in a function's type parameter list without an explicit type
argument, then the type argument is the type parameter being constrained.*
That means you can write
type Comparer[T any] interface {
Compare(T) int
}
func Min[T Comparer](x, y T) bool {
if x.Compare(y) < 0 {
return x
}
return y
}
Applying the same rule to type lists and type switches you should be able
to write
type Comparer[T any] interface {
Compare(T) int
}
type CompareConstraints interface {
type int, int8, …, float64, string, Comparer
}
func Min[T CompareConstraints](x, y T) bool {
switch T {
case int:
…
…
case Comparer:
if x.Compare(y) < 0 {
return x
}
return y
}
}
But the current proposal does not allow interfaces in type lists.
On Monday, 24 August 2020 at 07:09:15 UTC+1 rog wrote:
> On Mon, 24 Aug 2020 at 06:35, Denis Cheremisov <[email protected]>
> wrote:
>
>> I probably didn't read what you have wrote in the first message carefuly
>> enough. Does it mean something like that will work
>>
>> type SomeTypes interface {
>> type int, float32, float64
>> }
>>
>> func Min[T SomeTypes](x, y T) T {
>> switch T {
>> case int:
>> if x < y {
>> return x
>> }
>> return y
>> case float32:
>> return math.Min(float64(x), float64(y))
>> case float64:
>> return math.Min(x, y)
>> }
>> }
>>
>
> This was discussed above.
>
> I don't believe you can do that. I didn't see any suggestion that knowing
> the type implies the ability
> to convert from the generic type to the known underlying type.
>
>>
>> Would something like below work as well?
>>
>> type Compare[T any] interface {
>> Compare(x, y T) int
>> }
>>
>> type CompareConstraints[T any] {
>> type int, int8, …, float64, string, Compare[T]
>> }
>>
>> func Min[T CompareConstraints]Min(x, y T) bool {
>> switch T {
>> case int:
>> …
>> …
>> case Compare[T]:
>> return x.Compare(y) < 0
>> }
>> }
>>
>
> No. As proposed, the type switch doesn't change anything about the type T.
>
> Also, AIUI that type list wouldn't be very useful in practice, because
> using that interface type in the type list would only allow types whose
> underlying type is exactly Compare[T], which doesn't include any
> non-interface types or interface types that have more methods than just
> Compare.
>
> cheers,
> rog.
>
>
--
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 [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/03342d1f-5c82-40e6-98fc-18e95bfd183cn%40googlegroups.com.