Skip to content

Commit 2552a90

Browse files
committed
feat: update go smaples with our class discussion
1 parent 276851a commit 2552a90

File tree

3 files changed

+33
-8
lines changed

3 files changed

+33
-8
lines changed

08-arrays-and-slices/main.go

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,25 +19,34 @@ func main() {
1919
fmt.Printf("s2: %v\n", s2)
2020
fmt.Printf("s1 after \"s2[0] = 10\": %v\n", s1)
2121

22+
// append a new element into our newly created slice.
23+
s2 = append(s2, 120)
24+
fmt.Printf("s2: %v\n", s2)
25+
fmt.Printf("s1 after \"append(s2, 120)\": %v\n", s1)
26+
27+
// create another slice from middle of s1
28+
s3 := s1[2:4]
29+
fmt.Printf("s3: %v, cap(s3): %d, len(s3): %d\n", s3, cap(s3), len(s3))
30+
2231
a1 := [3]int{1, 2, 3}
2332

24-
s3 := a1[1:3]
25-
s3[0] = 20
33+
s4 := a1[1:3]
34+
s4[0] = 20
2635

27-
fmt.Printf("s3: %v\n", s3)
36+
fmt.Printf("s4: %v\n", s4)
2837
fmt.Printf("a1 after \"s3[0] = 20\": %v\n", a1)
2938

30-
s4 := s3
39+
s5 := s4
3140

3241
// compile error: slice can only be compared to nil
33-
// fmt.Printf("s4 ? s3: %v\n", s4 == s3)
34-
fmt.Printf("s4: %v\n", s4)
42+
// fmt.Printf("s5 ? s4: %v\n", s5 == s4)
43+
fmt.Printf("s5: %v\n", s5)
3544

3645
// panic: runtime error: index out of range [3] with length 2
37-
// fmt.Printf("invalid access to slice \"s4[3]\": %d", s4[3])
46+
// fmt.Printf("invalid access to slice \"s5[3]\": %d", s5[3])
3847

3948
// compile error: invalid array index 3 (out of bounds for 3-element array)
4049
// fmt.Printf("invalid access to array \"a1[3]\": %d", a1[3])
4150

42-
fmt.Printf("s4[1:]: %v\n", s4[1:])
51+
fmt.Printf("s5[1:]: %v\n", s5[1:])
4352
}

09-map/main.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,12 @@ func main() {
4545
if ok {
4646
fmt.Printf("opinions[%s] = %v\n", "Hesam", opinion)
4747
}
48+
49+
delete(opinions, "Parham")
50+
delete(opinions, "Parham")
51+
52+
_, ok = opinions["Parham"]
53+
if !ok {
54+
fmt.Printf("opinions[%s] does not exist\n", "Parham")
55+
}
4856
}

10-structs/main.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ type Student struct {
66
Name string
77
Family string
88
age int
9+
10+
// uncomment the following line to remove the comparablity.
11+
// justForFun []int
912
}
1013

1114
// New is a popular pattern to create types
@@ -37,6 +40,11 @@ func main() {
3740
age: 27,
3841
}
3942

43+
newS := s
44+
if newS == s {
45+
fmt.Println("we can compare student structs")
46+
}
47+
4048
fmt.Println(s)
4149

4250
s.nothing()

0 commit comments

Comments
 (0)