Skip to content

Commit e956408

Browse files
committed
added interfaces basics under go_basics module which teaches why interfaces are useful with examples
1 parent fa23cff commit e956408

File tree

3 files changed

+88
-0
lines changed

3 files changed

+88
-0
lines changed

go_basics/go.work

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use (
77
./defer_panic_recover
88
./functions
99
./gomaps
10+
./interfaces
1011
./loops
1112
./methods
1213
./numeric_constants

go_basics/interfaces/go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module anarchymonkey.com/go-basics/interfaces
2+
3+
go 1.20

go_basics/interfaces/interfaces.go

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"math"
6+
)
7+
8+
// An interface is a type which can hold any types that can implement the methods inside it
9+
10+
// let us go through an example
11+
12+
// Animal can be an interface, an animals
13+
14+
type Shape interface {
15+
calcArea() float64
16+
}
17+
18+
type Square struct {
19+
length int
20+
}
21+
22+
type Circle struct {
23+
radius int
24+
}
25+
26+
type Rectangle struct {
27+
Width int
28+
Height int
29+
}
30+
31+
func printArea(s Shape) {
32+
fmt.Println("The area is", s.calcArea())
33+
}
34+
35+
func main() {
36+
var s []Shape
37+
var a Shape
38+
39+
var circle Circle = Circle{
40+
radius: 25,
41+
}
42+
43+
var square Square = Square{
44+
length: 10,
45+
}
46+
47+
// var rect Rectangle = Rectangle{
48+
// Width: 10,
49+
// Height: 100,
50+
// }
51+
52+
var rect_v1 Rectangle = Rectangle{
53+
Width: 100,
54+
Height: 0,
55+
}
56+
57+
// a = rect
58+
a = &rect_v1
59+
60+
printArea(a)
61+
62+
// adding multiple shapes so that we can actually encapsulate the logic
63+
s = []Shape{
64+
&square,
65+
&circle,
66+
}
67+
68+
for _, shape := range s {
69+
printArea(shape)
70+
}
71+
72+
}
73+
74+
func (s *Square) calcArea() float64 {
75+
return float64(s.length) * float64(s.length)
76+
}
77+
78+
func (c *Circle) calcArea() float64 {
79+
return float64(c.radius) * float64(c.radius) * math.Pi
80+
}
81+
82+
func (r *Rectangle) calcArea() float64 {
83+
return float64(r.Width) * float64(r.Height)
84+
}

0 commit comments

Comments
 (0)