Skip to content

Commit

Permalink
feat: update go smaples with our class discussion
Browse files Browse the repository at this point in the history
  • Loading branch information
1995parham committed Oct 24, 2023
1 parent 276851a commit 2552a90
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 8 deletions.
25 changes: 17 additions & 8 deletions 08-arrays-and-slices/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:])
}
8 changes: 8 additions & 0 deletions 09-map/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
8 changes: 8 additions & 0 deletions 10-structs/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down

0 comments on commit 2552a90

Please sign in to comment.