Skip to content

Commit f04b2eb

Browse files
committed
added more examples of interfaces along with nil and type switches and type assertion exercises
1 parent e956408 commit f04b2eb

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed

go_basics/interfaces/interfaces.go

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,58 @@ func printArea(s Shape) {
3232
fmt.Println("The area is", s.calcArea())
3333
}
3434

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+
3587
func main() {
3688
var s []Shape
3789
var a Shape
@@ -69,6 +121,39 @@ func main() {
69121
printArea(shape)
70122
}
71123

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+
72157
}
73158

74159
func (s *Square) calcArea() float64 {
@@ -82,3 +167,17 @@ func (c *Circle) calcArea() float64 {
82167
func (r *Rectangle) calcArea() float64 {
83168
return float64(r.Width) * float64(r.Height)
84169
}
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

Comments
 (0)