| 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 |
|
| 41 |
|
| 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 |
|
| 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 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 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 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
} |
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|