-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
104 lines (83 loc) · 1.88 KB
/
main.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"fmt"
"math"
)
// a. Declaration
type Rectangle struct {
Width float64
Height float64
}
// Method with value receiver
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
// b. Pointer receiver
func (r *Rectangle) Scale(factor float64) {
r.Width *= factor
r.Height *= factor
}
// c. Methods on different types
// i. Method on basic data type
type MyFloat float64
func (f MyFloat) Abs() float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
}
// ii. Method on composite type (slice)
type IntSlice []int
func (is IntSlice) Sum() int {
total := 0
for _, v := range is {
total += v
}
return total
}
// iii. Method on function type
type MathFunc func(float64) float64
func (f MathFunc) Apply(x float64) float64 {
return f(x)
}
// d. Method of embedded types
type Shape interface {
Area() float64
}
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
// Embedding Circle in a new type
type ColoredCircle struct {
Circle
Color string
}
// i. Method resolution process
// ii. Polymorphism
func PrintArea(s Shape) {
fmt.Printf("Area: %f\n", s.Area())
}
func main() {
// Using Rectangle methods
r := Rectangle{Width: 10, Height: 5}
fmt.Printf("Rectangle Area: %f\n", r.Area())
r.Scale(2)
fmt.Printf("Scaled Rectangle: %+v\n", r)
// Using MyFloat method
f := MyFloat(-4.5)
fmt.Printf("Absolute value: %f\n", f.Abs())
// Using IntSlice method
is := IntSlice{1, 2, 3, 4, 5}
fmt.Printf("Sum of slice: %d\n", is.Sum())
// Using MathFunc method
square := MathFunc(func(x float64) float64 { return x * x })
fmt.Printf("Square of 3: %f\n", square.Apply(3))
// Using embedded type and demonstrating polymorphism
c := Circle{Radius: 5}
cc := ColoredCircle{Circle: Circle{Radius: 7}, Color: "Red"}
PrintArea(c)
PrintArea(cc) // ColoredCircle inherits Area() method from Circle
}