modernc.org/gc@v1.0.1-0.20240304020402-f0dba7c97c2b/testdata/errchk/test/interface/convert.go (about) 1 // run 2 3 // Copyright 2009 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 all the different interface conversion runtime functions. 8 9 package main 10 11 type Stringer interface { 12 String() string 13 } 14 type StringLengther interface { 15 String() string 16 Length() int 17 } 18 type Empty interface{} 19 20 type T string 21 22 func (t T) String() string { 23 return string(t) 24 } 25 func (t T) Length() int { 26 return len(t) 27 } 28 29 type U string 30 31 func (u U) String() string { 32 return string(u) 33 } 34 35 var t = T("hello") 36 var u = U("goodbye") 37 var e Empty 38 var s Stringer = t 39 var sl StringLengther = t 40 var i int 41 var ok bool 42 43 func hello(s string) { 44 if s != "hello" { 45 println("not hello: ", s) 46 panic("fail") 47 } 48 } 49 50 func five(i int) { 51 if i != 5 { 52 println("not 5: ", i) 53 panic("fail") 54 } 55 } 56 57 func true(ok bool) { 58 if !ok { 59 panic("not true") 60 } 61 } 62 63 func false(ok bool) { 64 if ok { 65 panic("not false") 66 } 67 } 68 69 func main() { 70 // T2I 71 s = t 72 hello(s.String()) 73 74 // I2T 75 t = s.(T) 76 hello(t.String()) 77 78 // T2E 79 e = t 80 81 // E2T 82 t = e.(T) 83 hello(t.String()) 84 85 // T2I again 86 sl = t 87 hello(sl.String()) 88 five(sl.Length()) 89 90 // I2I static 91 s = sl 92 hello(s.String()) 93 94 // I2I dynamic 95 sl = s.(StringLengther) 96 hello(sl.String()) 97 five(sl.Length()) 98 99 // I2E (and E2T) 100 e = s 101 hello(e.(T).String()) 102 103 // E2I 104 s = e.(Stringer) 105 hello(s.String()) 106 107 // I2T2 true 108 t, ok = s.(T) 109 true(ok) 110 hello(t.String()) 111 112 // I2T2 false 113 _, ok = s.(U) 114 false(ok) 115 116 // I2I2 true 117 sl, ok = s.(StringLengther) 118 true(ok) 119 hello(sl.String()) 120 five(sl.Length()) 121 122 // I2I2 false (and T2I) 123 s = u 124 sl, ok = s.(StringLengther) 125 false(ok) 126 127 // E2T2 true 128 t, ok = e.(T) 129 true(ok) 130 hello(t.String()) 131 132 // E2T2 false 133 i, ok = e.(int) 134 false(ok) 135 136 // E2I2 true 137 sl, ok = e.(StringLengther) 138 true(ok) 139 hello(sl.String()) 140 five(sl.Length()) 141 142 // E2I2 false (and T2E) 143 e = u 144 sl, ok = e.(StringLengther) 145 false(ok) 146 }