1
2
3
4
5
6
7
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
71 s = t
72 hello(s.String())
73
74
75 t = s.(T)
76 hello(t.String())
77
78
79 e = t
80
81
82 t = e.(T)
83 hello(t.String())
84
85
86 sl = t
87 hello(sl.String())
88 five(sl.Length())
89
90
91 s = sl
92 hello(s.String())
93
94
95 sl = s.(StringLengther)
96 hello(sl.String())
97 five(sl.Length())
98
99
100 e = s
101 hello(e.(T).String())
102
103
104 s = e.(Stringer)
105 hello(s.String())
106
107
108 t, ok = s.(T)
109 true(ok)
110 hello(t.String())
111
112
113 _, ok = s.(U)
114 false(ok)
115
116
117 sl, ok = s.(StringLengther)
118 true(ok)
119 hello(sl.String())
120 five(sl.Length())
121
122
123 s = u
124 sl, ok = s.(StringLengther)
125 false(ok)
126
127
128 t, ok = e.(T)
129 true(ok)
130 hello(t.String())
131
132
133 i, ok = e.(int)
134 false(ok)
135
136
137 sl, ok = e.(StringLengther)
138 true(ok)
139 hello(sl.String())
140 five(sl.Length())
141
142
143 e = u
144 sl, ok = e.(StringLengther)
145 false(ok)
146 }
147
View as plain text