| 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 |
func f[T any](x interface{}) T { |
| 10 |
return x.(T) |
| 11 |
} |
| 12 |
func f2[T any](x interface{}) (T, bool) { |
| 13 |
t, ok := x.(T) |
| 14 |
return t, ok |
| 15 |
} |
| 16 |
|
| 17 |
type I interface { |
| 18 |
foo() |
| 19 |
} |
| 20 |
|
| 21 |
type myint int |
| 22 |
|
| 23 |
func (myint) foo() { |
| 24 |
} |
| 25 |
|
| 26 |
type myfloat float64 |
| 27 |
|
| 28 |
func (myfloat) foo() { |
| 29 |
} |
| 30 |
|
| 31 |
func g[T I](x I) T { |
| 32 |
return x.(T) |
| 33 |
} |
| 34 |
func g2[T I](x I) (T, bool) { |
| 35 |
t, ok := x.(T) |
| 36 |
return t, ok |
| 37 |
} |
| 38 |
|
| 39 |
func h[T any](x interface{}) struct{ a, b T } { |
| 40 |
return x.(struct{ a, b T }) |
| 41 |
} |
| 42 |
|
| 43 |
func k[T any](x interface{}) interface{ bar() T } { |
| 44 |
return x.(interface{ bar() T }) |
| 45 |
} |
| 46 |
|
| 47 |
type mybar int |
| 48 |
|
| 49 |
func (x mybar) bar() int { |
| 50 |
return int(x) |
| 51 |
} |
| 52 |
|
| 53 |
func main() { |
| 54 |
var i interface{} = int(3) |
| 55 |
var j I = myint(3) |
| 56 |
var x interface{} = float64(3) |
| 57 |
var y I = myfloat(3) |
| 58 |
|
| 59 |
println(f[int](i)) |
| 60 |
shouldpanic(func() { f[int](x) }) |
| 61 |
println(f2[int](i)) |
| 62 |
println(f2[int](x)) |
| 63 |
|
| 64 |
println(g[myint](j)) |
| 65 |
shouldpanic(func() { g[myint](y) }) |
| 66 |
println(g2[myint](j)) |
| 67 |
println(g2[myint](y)) |
| 68 |
|
| 69 |
println(h[int](struct{ a, b int }{3, 5}).a) |
| 70 |
|
| 71 |
println(k[int](mybar(3)).bar()) |
| 72 |
|
| 73 |
type large struct {a,b,c,d,e,f int} |
| 74 |
println(f[large](large{}).a) |
| 75 |
l2, ok := f2[large](large{}) |
| 76 |
println(l2.a, ok) |
| 77 |
} |
| 78 |
func shouldpanic(x func()) { |
| 79 |
defer func() { |
| 80 |
e := recover() |
| 81 |
if e == nil { |
| 82 |
panic("didn't panic") |
| 83 |
} |
| 84 |
}() |
| 85 |
x() |
| 86 |
} |