From 2552a907bde014d6fa3150d49859f2c504a15d19 Mon Sep 17 00:00:00 2001 From: Parham Alvani Date: Tue, 24 Oct 2023 19:02:02 +0000 Subject: [PATCH] feat: update go smaples with our class discussion --- 08-arrays-and-slices/main.go | 25 +++++++++++++++++-------- 09-map/main.go | 8 ++++++++ 10-structs/main.go | 8 ++++++++ 3 files changed, 33 insertions(+), 8 deletions(-) diff --git a/08-arrays-and-slices/main.go b/08-arrays-and-slices/main.go index 9f64df1..3adabf7 100644 --- a/08-arrays-and-slices/main.go +++ b/08-arrays-and-slices/main.go @@ -19,25 +19,34 @@ func main() { fmt.Printf("s2: %v\n", s2) fmt.Printf("s1 after \"s2[0] = 10\": %v\n", s1) + // append a new element into our newly created slice. + s2 = append(s2, 120) + fmt.Printf("s2: %v\n", s2) + fmt.Printf("s1 after \"append(s2, 120)\": %v\n", s1) + + // create another slice from middle of s1 + s3 := s1[2:4] + fmt.Printf("s3: %v, cap(s3): %d, len(s3): %d\n", s3, cap(s3), len(s3)) + a1 := [3]int{1, 2, 3} - s3 := a1[1:3] - s3[0] = 20 + s4 := a1[1:3] + s4[0] = 20 - fmt.Printf("s3: %v\n", s3) + fmt.Printf("s4: %v\n", s4) fmt.Printf("a1 after \"s3[0] = 20\": %v\n", a1) - s4 := s3 + s5 := s4 // compile error: slice can only be compared to nil - // fmt.Printf("s4 ? s3: %v\n", s4 == s3) - fmt.Printf("s4: %v\n", s4) + // fmt.Printf("s5 ? s4: %v\n", s5 == s4) + fmt.Printf("s5: %v\n", s5) // panic: runtime error: index out of range [3] with length 2 - // fmt.Printf("invalid access to slice \"s4[3]\": %d", s4[3]) + // fmt.Printf("invalid access to slice \"s5[3]\": %d", s5[3]) // compile error: invalid array index 3 (out of bounds for 3-element array) // fmt.Printf("invalid access to array \"a1[3]\": %d", a1[3]) - fmt.Printf("s4[1:]: %v\n", s4[1:]) + fmt.Printf("s5[1:]: %v\n", s5[1:]) } diff --git a/09-map/main.go b/09-map/main.go index 264b21e..f9f4b65 100644 --- a/09-map/main.go +++ b/09-map/main.go @@ -45,4 +45,12 @@ func main() { if ok { fmt.Printf("opinions[%s] = %v\n", "Hesam", opinion) } + + delete(opinions, "Parham") + delete(opinions, "Parham") + + _, ok = opinions["Parham"] + if !ok { + fmt.Printf("opinions[%s] does not exist\n", "Parham") + } } diff --git a/10-structs/main.go b/10-structs/main.go index 857227b..b3c53c7 100644 --- a/10-structs/main.go +++ b/10-structs/main.go @@ -6,6 +6,9 @@ type Student struct { Name string Family string age int + + // uncomment the following line to remove the comparablity. + // justForFun []int } // New is a popular pattern to create types @@ -37,6 +40,11 @@ func main() { age: 27, } + newS := s + if newS == s { + fmt.Println("we can compare student structs") + } + fmt.Println(s) s.nothing()