github.com/traefik/yaegi@v0.15.1/_test/assert0.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "time" 6 ) 7 8 type MyWriter interface { 9 Write(p []byte) (i int, err error) 10 } 11 12 type DummyWriter interface { 13 Write(p []byte) (i int, err error) 14 } 15 16 type TestStruct struct{} 17 18 func (t TestStruct) Write(p []byte) (n int, err error) { 19 return len(p), nil 20 } 21 22 func usesWriter(w MyWriter) { 23 n, _ := w.Write([]byte("hello world")) 24 fmt.Println(n) 25 } 26 27 type MyStringer interface { 28 String() string 29 } 30 31 type DummyStringer interface { 32 String() string 33 } 34 35 func usesStringer(s MyStringer) { 36 fmt.Println(s.String()) 37 } 38 39 func main() { 40 // TODO(mpl): restore when we can deal with empty interface. 41 // var t interface{} 42 var t DummyWriter 43 t = TestStruct{} 44 var tw MyWriter 45 var ok bool 46 tw, ok = t.(MyWriter) 47 if !ok { 48 fmt.Println("TestStruct does not implement MyWriter") 49 } else { 50 fmt.Println("TestStruct implements MyWriter") 51 usesWriter(tw) 52 } 53 n, _ := t.(MyWriter).Write([]byte("hello world")) 54 fmt.Println(n) 55 56 // not redundant with the above, because it goes through a slightly different code path. 57 if _, ok := t.(MyWriter); !ok { 58 fmt.Println("TestStruct does not implement MyWriter") 59 return 60 } else { 61 fmt.Println("TestStruct implements MyWriter") 62 } 63 64 // TODO(mpl): restore 65 /* 66 t = 42 67 foo, ok := t.(MyWriter) 68 if !ok { 69 fmt.Println("42 does not implement MyWriter") 70 } else { 71 fmt.Println("42 implements MyWriter") 72 } 73 _ = foo 74 75 if _, ok := t.(MyWriter); !ok { 76 fmt.Println("42 does not implement MyWriter") 77 } else { 78 fmt.Println("42 implements MyWriter") 79 } 80 */ 81 82 // var tt interface{} 83 var tt DummyStringer 84 tt = time.Nanosecond 85 var myD MyStringer 86 myD, ok = tt.(MyStringer) 87 if !ok { 88 fmt.Println("time.Nanosecond does not implement MyStringer") 89 } else { 90 fmt.Println("time.Nanosecond implements MyStringer") 91 usesStringer(myD) 92 } 93 fmt.Println(tt.(MyStringer).String()) 94 95 if _, ok := tt.(MyStringer); !ok { 96 fmt.Println("time.Nanosecond does not implement MyStringer") 97 } else { 98 fmt.Println("time.Nanosecond implements MyStringer") 99 } 100 101 // TODO(mpl): restore 102 /* 103 tt = 42 104 bar, ok := tt.(MyStringer) 105 if !ok { 106 fmt.Println("42 does not implement MyStringer") 107 } else { 108 fmt.Println("42 implements MyStringer") 109 } 110 _ = bar 111 112 if _, ok := tt.(MyStringer); !ok { 113 fmt.Println("42 does not implement MyStringer") 114 } else { 115 fmt.Println("42 implements MyStringer") 116 } 117 */ 118 } 119 120 // Output: 121 // TestStruct implements MyWriter 122 // 11 123 // 11 124 // TestStruct implements MyWriter 125 // time.Nanosecond implements MyStringer 126 // 1ns 127 // 1ns 128 // time.Nanosecond implements MyStringer