Skip to content

Commit

Permalink
feat: Issue: Loop Struct Slice update (#32)
Browse files Browse the repository at this point in the history
  • Loading branch information
hhow09 authored Jan 21, 2025
1 parent 18481eb commit 462da03
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 113 deletions.
28 changes: 15 additions & 13 deletions examples/issue-loop-struct-slice/issue-loop-struct-slice.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
// interview questions:
// Challenge:
//
// What is expected output?
//
// How to fix this code?
//
// Reference: [Go Wiki: Range Clauses](https://go.dev/wiki/Range)
//
// Reference: [Should you use slices of pointers to structs?](https://www.willem.dev/articles/slice-of-pointers-structs/)
//
// Reference: [Go Spec: For statements](https://go.dev/ref/spec#For_statements)

package main

Expand All @@ -26,19 +32,23 @@ func main() {
fmt.Printf("player %s has score %d\n", p.name, p.score)
}

// (End of Question)
// (End of Challenge)
// ----------

// Explaination:
// The player struct is stored in the backing array of the slice players
//
// `p` is actually only a copy of the original player
// - The player struct is stored in the backing array of the slice players
//
// - p is declaredin in range clause using a form of [short variable declaration (:=)](https://go.dev/ref/spec#Short_variable_declarations). The variables have the types of their respective iteration values.
//
// - `p` is only a copy of the original player
//
// - when updating `p.score`, it only updates the "copy" of the player in the slice
for _, p := range players {
p.score += 10
}

// How to fix it?

fmt.Println("---- After fix ------")
// Directly access the player in the slice
for i := range players {
Expand All @@ -48,12 +58,4 @@ func main() {
for _, p := range players {
fmt.Printf("player %s has score %d\n", p.name, p.score)
}

// Output:
//
// player Bob has score 20
//
// player Alice has score 217
}

// Reference: [Should you use slices of pointers to structs?](https://www.willem.dev/articles/slice-of-pointers-structs/)
4 changes: 2 additions & 2 deletions examples/issue-loop-struct-slice/issue-loop-struct-slice.hash
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
1acf36d67df9c219102a45e722d1cbb38dbd8ce5
b5YAS_z1uop
7d7891806eda3e24148d21ce6a31e2fbaf3ea623
gb9N6mi5JjT
76 changes: 27 additions & 49 deletions public/issue-loop-struct-slice

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

76 changes: 27 additions & 49 deletions public/issue-loop-struct-slice.html

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 462da03

Please sign in to comment.