Source file test/typeparam/issue50002.go

     1  // run
     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 for cases where certain instantiations of a generic function (F in this
     8  // example) will always fail on a type assertion or mismatch on a type case.
     9  
    10  package main
    11  
    12  import "fmt"
    13  
    14  type S struct{}
    15  
    16  func (S) M() byte {
    17  	return 0
    18  }
    19  
    20  type I[T any] interface {
    21  	M() T
    22  }
    23  
    24  func F[T, A any](x I[T], shouldMatch bool) {
    25  	switch x.(type) {
    26  	case A:
    27  		if !shouldMatch {
    28  			fmt.Printf("wanted mis-match, got match")
    29  		}
    30  	default:
    31  		if shouldMatch {
    32  			fmt.Printf("wanted match, got mismatch")
    33  		}
    34  	}
    35  
    36  	_, ok := x.(A)
    37  	if ok != shouldMatch {
    38  		fmt.Printf("ok: got %v, wanted %v", ok, shouldMatch)
    39  	}
    40  
    41  	if !shouldMatch {
    42  		defer func() {
    43  			if shouldMatch {
    44  				fmt.Printf("Shouldn't have panicked")
    45  			}
    46  			recover()
    47  		}()
    48  	}
    49  	_ = x.(A)
    50  	if !shouldMatch {
    51  		fmt.Printf("Should have panicked")
    52  	}
    53  }
    54  
    55  func main() {
    56  	// Test instantiation where the type switch/type asserts can't possibly succeed
    57  	// (since string does not implement I[byte]).
    58  	F[byte, string](S{}, false)
    59  
    60  	// Test instantiation where the type switch/type asserts should succeed
    61  	// (since S does implement I[byte])
    62  	F[byte, S](S{}, true)
    63  	F[byte, S](I[byte](S{}), true)
    64  }
    65  

View as plain text