-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_structures.go
118 lines (100 loc) · 2.48 KB
/
data_structures.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
115
116
117
118
package main
import "fmt"
// A structure
type Rectangle struct {
width int
length int
}
func (r *Rectangle) updateWidth(width int) {
r.width = width
}
func (r *Rectangle) print() {
fmt.Printf("Length: %d Width %d\n", r.length, r.width)
}
//Functions with unknown number of arguments
//Variadic function
func addNumbers(args ...int) int {
sum := 0
for _, n := range args {
sum += n
}
return sum
}
func decrement() int {
a := 10
//closure function : function within function
d := func() {
a--
}
d()
d()
return a
}
func main() {
//Arrays
var arr [2]string
arr[0] = "Hello"
arr[1] = "Aanisha"
fmt.Println(arr)
//Slices - Method 1
slice := []int{1, 2, 3, 4, 5}
fmt.Println(slice)
//Slices - Method 2
g := make([]int, 5, 10)
s := g[2:4] //again slices using high low expression
s[0] = 10
s[1] = 11
g[4] = 14
fmt.Println(s, " capacity of s is ", cap(s))
a := s[:cap(s)]
//size of a will be 8 as it will take up complete capacity of s and in turn g
fmt.Println(a)
var pow = []int{1, 2, 4, 8, 16}
//range keyword is used to loop through each element in the slice pow
//n represents the index
//p represent the value in the index n
for n, p := range pow {
fmt.Printf("%d indexed value is %d\n", n, p)
}
//creating a new slice using one created earlier
new_slice := append(pow, 32, 64)
fmt.Println("The new slice is ", new_slice)
//copy one slice to another
copied_slice := make([]int, 2, 4)
copy(copied_slice, pow)
fmt.Println("Copied slice is ", copied_slice)
nil_slice1 := make([]int, 0, 0)
nil_slice2 := make([]int, 0, 4)
var nil_slice3 []int
switch {
case nil_slice1 == nil:
fmt.Println("nil_slice1 is nill")
case nil_slice2 == nil:
fmt.Println("nil_slice2 is nill")
case nil_slice3 == nil:
fmt.Println("nil_slice3 is nill")
default:
fmt.Println("None of the slices are nil!!")
}
//Demonstration of use of structures
r := Rectangle{10, 20}
r.print()
r.updateWidth(15)
r.print()
//Maps
var m = map[string]Rectangle{"Rect1": {1, 2}, "Rect2": {3, 4}}
fmt.Println(m)
delete(m, "Rect1")
x, ok := m["Rect1"]
fmt.Println("Value of Rect1: ", x, " Present: ", ok)
fmt.Println("Finally m is: ", m)
// calling function that take n number of arguments
fmt.Println("sum from 1 to 6 is ", addNumbers(1, 2, 3, 4, 5, 6))
fmt.Println("Decrement value of a: ", decrement())
// Pointers
var q *string
var p_string = "Hello World"
q = &p_string
fmt.Println("Value of p_string: ", p_string , ", Value from pointer: ", *q)
fmt.Println("Value of pointer", q)
}