Source file test/typeparam/typeswitch3.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  package main
     8  
     9  type I interface{ foo() int }
    10  type J interface {
    11  	I
    12  	bar()
    13  }
    14  
    15  type myint int
    16  
    17  func (x myint) foo() int { return int(x) }
    18  
    19  type myfloat float64
    20  
    21  func (x myfloat) foo() int { return int(x) }
    22  
    23  type myint32 int32
    24  
    25  func (x myint32) foo() int { return int(x) }
    26  func (x myint32) bar()     {}
    27  
    28  func f[T I](i I) {
    29  	switch x := i.(type) {
    30  	case T:
    31  		println("T", x.foo())
    32  	case myint:
    33  		println("myint", x.foo())
    34  	default:
    35  		println("other", x.foo())
    36  	}
    37  }
    38  func main() {
    39  	f[myfloat](myint(6))
    40  	f[myfloat](myfloat(7))
    41  	f[myfloat](myint32(8))
    42  	f[myint32](myint32(8))
    43  	f[myint32](myfloat(7))
    44  	f[myint](myint32(9))
    45  	f[I](myint(10))
    46  	f[J](myint(11))
    47  	f[J](myint32(12))
    48  }
    49  

View as plain text