Thank you for your book - it's wonderful!
While reading, I noticed a small issue in the illustration of slice behavior in the section about mistake 20.
In Figure 4, it looks like the original underlying array has been modified - elements 3 and 4 are shown as inserted into it. However, when memory is reallocated during append, the original array should remain unchanged in that case. I thought this is minor thing, but may be worth mentioning.
I wasn’t sure whether I should start with an Issue or go straight to a Pull Request - apologies if this is too direct or even rude, but I’ve submitted a PR as an example: #119
I’m also including a code snippet below to demonstrate behavior. It shows that the original underlying array remains unchanged, and elements 3 and 4 are not inserted into it:
package main
import "fmt"
func main() {
s := make([]int, 4, 6)
s[1] = 1
s[3] = 2
sliceStats("Initial underlying array", s)
// no reassignment, to see old unerlying array
appendExample(s)
sliceStats("Old underlying array after append", s)
fmt.Printf("No 3 and 4 in old underlying array*\n\n")
// just for illustration
changeUnderlyingArray(s)
sliceStats("Changed underlying array in main", s)
}
func appendExample(s []int) {
s = append(s, 3, 4, 5)
sliceStats("New underlying array after append", s)
}
func changeUnderlyingArray(s []int) {
s = append(s, 42)
sliceStats("Changed underlying array in func", s)
}
func sliceStats(text string, s []int) {
fmt.Printf("%s:\n\tlen = %d, cap = %d\n", text, len(s), cap(s))
fmt.Printf("\tTo len: %v\n", s)
fmt.Printf("\tTo cap: %v\n", s[:cap(s)])
}
And output:
go run .
Initial underlying array:
len = 4, cap = 6
To len: [0 1 0 2]
To cap: [0 1 0 2 0 0]
New underlying array after append:
len = 7, cap = 12
To len: [0 1 0 2 3 4 5]
To cap: [0 1 0 2 3 4 5 0 0 0 0 0]
Old underlying array after append:
len = 4, cap = 6
To len: [0 1 0 2]
To cap: [0 1 0 2 0 0]
No 3 and 4 in old underlying array*
Changed underlying array in func:
len = 5, cap = 6
To len: [0 1 0 2 42]
To cap: [0 1 0 2 42 0]
Changed underlying array in main:
len = 4, cap = 6
To len: [0 1 0 2]
To cap: [0 1 0 2 42 0]
Thank you for your book - it's wonderful!
While reading, I noticed a small issue in the illustration of slice behavior in the section about mistake 20.
In Figure 4, it looks like the original underlying array has been modified - elements 3 and 4 are shown as inserted into it. However, when memory is reallocated during append, the original array should remain unchanged in that case. I thought this is minor thing, but may be worth mentioning.
I wasn’t sure whether I should start with an Issue or go straight to a Pull Request - apologies if this is too direct or even rude, but I’ve submitted a PR as an example: #119
I’m also including a code snippet below to demonstrate behavior. It shows that the original underlying array remains unchanged, and elements 3 and 4 are not inserted into it:
And output: