@@ -32,6 +32,58 @@ func printArea(s Shape) {
32
32
fmt .Println ("The area is" , s .calcArea ())
33
33
}
34
34
35
+ type DummyInterface interface {
36
+ validateSquare ()
37
+ }
38
+
39
+ func typeAssertions () {
40
+ var inter interface {} = "hello"
41
+
42
+ defer func () {
43
+ // this recoveres the panic function if any
44
+ println ("Recovered" , recover ())
45
+ }()
46
+
47
+ s , ok := inter .(string )
48
+
49
+ if ok {
50
+ fmt .Println ("interface type assertion" , s )
51
+ }
52
+
53
+ f , floatOk := inter .(float64 )
54
+
55
+ if floatOk {
56
+ fmt .Println ("Suddenly the type changed to " , f )
57
+ } else {
58
+ fmt .Println ("Cannot implement other types than the defined one" )
59
+ }
60
+
61
+ }
62
+
63
+ func typeSwitches (i interface {}) {
64
+
65
+ switch v := i .(type ) {
66
+ case * Square :
67
+ {
68
+ fmt .Println ("This is a square" , v .length )
69
+ }
70
+ case * Circle :
71
+ {
72
+ fmt .Println ("This is a circle" , v .radius , v .calcArea ())
73
+ }
74
+ default :
75
+ {
76
+ fmt .Println ("This is some unknown type" , v )
77
+ }
78
+ }
79
+ }
80
+
81
+ type IPAddr [4 ]byte
82
+
83
+ func (ip IPAddr ) String () string {
84
+ return fmt .Sprintf ("%d.%d.%d.%d" , ip [0 ], ip [1 ], ip [2 ], ip [3 ])
85
+ }
86
+
35
87
func main () {
36
88
var s []Shape
37
89
var a Shape
@@ -69,6 +121,39 @@ func main() {
69
121
printArea (shape )
70
122
}
71
123
124
+ // interface values with nil underlying values
125
+ var nullSquare * Square = & Square {
126
+ length : 20 ,
127
+ }
128
+ var b DummyInterface = nullSquare
129
+
130
+ b .validateSquare ()
131
+
132
+ // type assertion
133
+
134
+ typeAssertions ()
135
+
136
+ // typeswitches
137
+
138
+ for _ , shape := range s {
139
+ typeSwitches (shape )
140
+ }
141
+
142
+ // stringer
143
+
144
+ fmt .Println (& square )
145
+
146
+ // stringer exercise
147
+
148
+ var ipAddrStore map [string ]IPAddr = map [string ]IPAddr {
149
+ "loopback" : {127 , 0 , 0 , 1 },
150
+ "googleDNS" : {8 , 8 , 8 , 8 },
151
+ }
152
+
153
+ for _ , value := range ipAddrStore {
154
+ fmt .Println (value )
155
+ }
156
+
72
157
}
73
158
74
159
func (s * Square ) calcArea () float64 {
@@ -82,3 +167,17 @@ func (c *Circle) calcArea() float64 {
82
167
func (r * Rectangle ) calcArea () float64 {
83
168
return float64 (r .Width ) * float64 (r .Height )
84
169
}
170
+
171
+ func (s * Square ) validateSquare () {
172
+
173
+ if s == nil {
174
+ fmt .Println ("nil" )
175
+ return
176
+ }
177
+
178
+ fmt .Println ("Its a validated square" )
179
+ }
180
+
181
+ func (s * Square ) String () string {
182
+ return fmt .Sprintf ("The square value is %d" , s .length )
183
+ }
0 commit comments