-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
114 lines (96 loc) · 2.31 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
105
106
107
108
109
110
111
112
113
114
package main
import "fmt"
// Basic struct definition
type contactInfo struct {
address string
zip int
}
// Struct embedding for composition
type person struct {
name string
age int
contactInfo // Embedded struct
}
// Struct method
func (p person) print() {
fmt.Printf("%+v\n", p)
}
// Pointer receiver method
func (p *person) updateName(n string) {
// (*p).name = n //This also works
p.name = n
}
func main() {
// Struct initialization
p := person{
"saksham",
18,
contactInfo{
"pune",
411057,
},
}
// Struct initialization with field names
p2 := person{
age: 33,
name: "anuj",
contactInfo: contactInfo{
"pune",
411057,
},
}
fmt.Printf("%+v\n", p)
p2.print()
// Pointer to struct
p3 := &p2
p3.updateName("alex1")
p2.print()
p2.updateName("alex2") //without & also works the same way
p2.print()
// New type of primitive types
type Celsius float64
type Fahrenheit float64
// Declaration of struct
type Rectangle struct {
Width float64
Height float64
}
// Initialization of struct
r1 := Rectangle{Width: 10, Height: 5}
r2 := Rectangle{10, 5} // Order matters when not using field names
// Setting and getting struct value
r1.Width = 15
fmt.Printf("Rectangle 1 width: %f\n", r1.Width)
// Pointer to struct
r3 := &Rectangle{Width: 20, Height: 10}
r3.Height = 15 // Automatically dereferenced, same as (*r3).Height = 15
fmt.Printf("Rectangle 3: %+v\n", r3)
// Struct equality
fmt.Printf("r1 == r2: %v\n", r1 == r2)
fmt.Printf("r1 == *r3: %v\n", r1 == *r3)
// Using the new type
var temp Celsius = 100
fmt.Printf("Temperature in Celsius: %.2f°C\n", temp)
// Function to convert Celsius to Fahrenheit
celsiusToFahrenheit := func(c Celsius) Fahrenheit {
return Fahrenheit(c*9/5 + 32)
}
fmt.Printf("Temperature in Fahrenheit: %.2f°F\n", celsiusToFahrenheit(temp))
// Anonymous struct
point := struct {
X, Y int
}{10, 20}
fmt.Printf("Anonymous struct: %+v\n", point)
// Struct with tags
type User struct {
Name string `json:"name" validate:"required"`
Email string `json:"email" validate:"required,email"`
}
user := User{Name: "John Doe", Email: "[email protected]"}
fmt.Printf("User: %+v\n", user)
// Struct initialization with new
newPerson := new(person)
newPerson.name = "Alice"
newPerson.age = 25
fmt.Printf("New person: %+v\n", newPerson)
}