Source file test/typeparam/issue50177.go

     1  // compile
     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  package main
     8  
     9  import "fmt"
    10  
    11  type Fn[T any] func(T)
    12  type FnErr[T any] func(T) error
    13  
    14  // Test that local generic types across functions don't conflict, and they also don't
    15  // conflict with local non-generic types and local variables.
    16  func caller0() {
    17  	type X[T any] struct {
    18  		fn Fn[int]
    19  	}
    20  
    21  	x := X[int]{func(v int) { fmt.Println(v) }}
    22  	x.fn(0)
    23  }
    24  
    25  func caller1(val int) {
    26  	type X[T any] struct {
    27  		fn FnErr[int]
    28  	}
    29  
    30  	x := X[int]{func(v int) error { fmt.Println(v); return nil }}
    31  	x.fn(0)
    32  }
    33  
    34  func caller1a(val int) {
    35  	type X struct {
    36  		fn func(float64) error
    37  	}
    38  
    39  	x := X{func(v float64) error { fmt.Println(v); return nil }}
    40  	x.fn(float64(3.2))
    41  }
    42  
    43  func caller1b(val int) {
    44  	type Y struct {
    45  		fn func(float64) error
    46  	}
    47  
    48  	X := Y{func(v float64) error { fmt.Println(v); return nil }}
    49  	X.fn(float64(3.2))
    50  }
    51  
    52  // Test that local generic types within different if clauses don't conflict.
    53  func caller2(val int) {
    54  	if val > 2 {
    55  		type X[T any] struct {
    56  			fn func(v int) float64
    57  		}
    58  
    59  		x := X[int]{func(v int) float64 { fmt.Println(v); return 1.5 }}
    60  		x.fn(0)
    61  	} else {
    62  		type X[T any] struct {
    63  			fn func(v int) int
    64  		}
    65  		x := X[int]{func(v int) int { fmt.Println(v); return 5 }}
    66  		x.fn(0)
    67  	}
    68  }
    69  
    70  // Test that local generic types within different cases don't conflict with each
    71  // other or with local non-generic types or local variables.
    72  func caller3(val int) {
    73  	switch val {
    74  	case 0:
    75  		type X[T any] struct {
    76  			fn func(v int) float64
    77  		}
    78  
    79  		x := X[int]{func(v int) float64 { fmt.Println(v); return 1.5 }}
    80  		x.fn(0)
    81  	case 1:
    82  		type X[T any] struct {
    83  			fn func(v int) int
    84  		}
    85  		x := X[int]{func(v int) int { fmt.Println(v); return 5 }}
    86  		x.fn(0)
    87  	case 2:
    88  		type X struct {
    89  			fn func(v int) bool
    90  		}
    91  		x := X{func(v int) bool { fmt.Println(v); return false }}
    92  		x.fn(0)
    93  	case 3:
    94  		type Y struct {
    95  			fn func(v int) bool
    96  		}
    97  		X := Y{func(v int) bool { fmt.Println(v); return false }}
    98  		X.fn(0)
    99  
   100  	}
   101  }
   102  

View as plain text