Skip to content

fix(20): remove elements 3 and 4 from old array of figure 4#119

Open
AnruKitakaze wants to merge 2 commits into
teivah:masterfrom
AnruKitakaze:master
Open

fix(20): remove elements 3 and 4 from old array of figure 4#119
AnruKitakaze wants to merge 2 commits into
teivah:masterfrom
AnruKitakaze:master

Conversation

@AnruKitakaze
Copy link
Copy Markdown

I found an issue in Figure 4: elements 3 and 4 (indexes 4 and 5 respectively) should not appear in the original array. These slots remain uninitialized (zero values in example below), and the new elements should only exists in the newely allocated underlying array.

Here's a minimal example that demonstrates this behaviour:

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)])
}

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]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant