File tree 3 files changed +88
-0
lines changed
3 files changed +88
-0
lines changed Original file line number Diff line number Diff line change 7
7
./defer_panic_recover
8
8
./functions
9
9
./gomaps
10
+ ./interfaces
10
11
./loops
11
12
./methods
12
13
./numeric_constants
Original file line number Diff line number Diff line change
1
+ module anarchymonkey.com/go-basics/interfaces
2
+
3
+ go 1.20
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments