From cf4b6dc48eba807e7d85fb6ab30cbbbdb143c552 Mon Sep 17 00:00:00 2001 From: Keith Randall Date: Fri, 4 Jun 2021 22:54:08 -0700 Subject: [dev.typeparams] cmd/compile: allow conversions from type parameter to interface When converting from a type param to an interface, allow it if the type bound implements that interface. Query: some conversions go through this path, some use another path? The test does var i interface{foo()int} = x but i := (interface{foo()int})(x) works at tip. Change-Id: I84d497e5228c0e1d1c9d76ffebaedce09dc45e8e Reviewed-on: https://go-review.googlesource.com/c/go/+/325409 Trust: Keith Randall Trust: Dan Scales Run-TryBot: Keith Randall TryBot-Result: Go Bot Reviewed-by: Dan Scales --- test/typeparam/ifaceconv.go | 58 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 test/typeparam/ifaceconv.go (limited to 'test/typeparam') diff --git a/test/typeparam/ifaceconv.go b/test/typeparam/ifaceconv.go new file mode 100644 index 0000000000..0b0776815c --- /dev/null +++ b/test/typeparam/ifaceconv.go @@ -0,0 +1,58 @@ +// run -gcflags=-G=3 + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Test that we can convert type parameters to both empty +// and nonempty interfaces, and named and nonnamed versions +// thereof. + +package main + +import "fmt" + +type E interface{} + +func f[T any](x T) interface{} { + var i interface{} = x + return i +} +func g[T any](x T) E { + var i E = x + return i +} + +type C interface { + foo() int +} + +type myInt int + +func (x myInt) foo() int { + return int(x+1) +} + +func h[T C](x T) interface{foo() int} { + var i interface{foo()int} = x + return i +} +func i[T C](x T) C { + var i C = x + return i +} + +func main() { + if got, want := f[int](7), 7; got != want { + panic(fmt.Sprintf("got %d want %d", got, want)) + } + if got, want := g[int](7), 7; got != want { + panic(fmt.Sprintf("got %d want %d", got, want)) + } + if got, want := h[myInt](7).foo(), 8; got != want { + panic(fmt.Sprintf("got %d want %d", got, want)) + } + if got, want := i[myInt](7).foo(), 8; got != want { + panic(fmt.Sprintf("got %d want %d", got, want)) + } +} -- cgit v1.3-5-g9baa