Source file test/typeparam/mdempsky/15.go

     1  // run -goexperiment fieldtrack
     2  
     3  // Copyright 2021 The Go Authors. All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  // Test that generics, promoted methods, and //go:nointerface
     8  // interoperate as expected.
     9  
    10  package main
    11  
    12  import (
    13  	"reflect"
    14  )
    15  
    16  func TypeString[T any]() string {
    17  	return reflect.TypeOf(new(T)).Elem().String()
    18  }
    19  
    20  func Test[T, Bad, Good any]() {
    21  	switch interface{}(new(T)).(type) {
    22  	case Bad:
    23  		println("FAIL:", TypeString[T](), "matched", TypeString[Bad]())
    24  	case Good:
    25  		// ok
    26  	default:
    27  		println("FAIL:", TypeString[T](), "did not match", TypeString[Good]())
    28  	}
    29  }
    30  
    31  func TestE[T any]() { Test[T, interface{ EBad() }, interface{ EGood() }]() }
    32  func TestX[T any]() { Test[T, interface{ XBad() }, interface{ XGood() }]() }
    33  
    34  type E struct{}
    35  
    36  //go:nointerface
    37  func (E) EBad()  {}
    38  func (E) EGood() {}
    39  
    40  type X[T any] struct{ E }
    41  
    42  //go:nointerface
    43  func (X[T]) XBad()  {}
    44  func (X[T]) XGood() {}
    45  
    46  type W struct{ X[int] }
    47  
    48  func main() {
    49  	_ = E.EGood
    50  	_ = E.EBad
    51  
    52  	TestE[E]()
    53  
    54  	_ = X[int].EGood
    55  	_ = X[int].EBad
    56  	_ = X[int].XGood
    57  	_ = X[int].XBad
    58  
    59  	TestE[X[int]]()
    60  	TestX[X[int]]()
    61  
    62  	_ = W.EGood
    63  	_ = W.EBad
    64  	_ = W.XGood
    65  	_ = W.XBad
    66  
    67  	TestE[W]()
    68  	TestX[W]()
    69  }
    70  

View as plain text