-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinterface.go
56 lines (43 loc) · 810 Bytes
/
interface.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main
import (
"fmt"
"math"
)
type Drawable interface {
draw()
}
type Shape interface {
Area() float64
}
type Point struct {
X, Y int
}
type Square struct {
side float64
}
type Circle struct {
center Point
radius float64
}
// This method means type Circle implements the interface Shape
func (c Circle) Area() float64 {
return math.Pi * c.radius * c.radius
}
func (c Circle) draw() {
fmt.Println("Drawing circle")
}
func (s Square) Area() float64 {
return s.side * s.side
}
func printArea(s Shape) {
fmt.Println(s.Area())
}
func main() {
s := Square{side: 4}
c := Circle{Point{3, 6}, 7}
// Since both Square & Circle implement Shape interface, we can do the following:
printArea(s) // 16
printArea(c) // 153.93804002589985
var d Drawable = c
d.draw() // Drawing circle
}