karlseguin / the-little-go-book

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Chapter 3 Arrays example func removeAtIndex changes array order

mdstaff opened this issue · comments

commented

Hello,

Thank you for writing this very helpful book. I am just starting to learn Go and found this chapter very useful. I was a bit intrigued by your example "removeAtIndex" as I often use slice and splice in other languages. I found it a bit unexpected when the return value of the array was not in its original order sans the value at position 2. I took the liberty of trying my hand at a similar example which might serve the same purpose.

func main() {
  scores := []int{1, 2, 3, 4, 5}
  scores = spliceAtIndex(scores, 2)
  fmt.Println(scores)
}

func removeAtIndex(source []int, index int) []int {
	lastIndex := len(source) - 1
	fmt.Println(lastIndex)
  //swap the last value and the value we want to remove
	source[index], source[lastIndex] = source[lastIndex], source[index]
	fmt.Println(source)
  return source[:lastIndex]
}

func spliceAtIndex(source []int, index int) []int {
  lastIndex := len(source) - 1
	fmt.Println(lastIndex)
  //swap the last value and the value we want to remove
	// source[index], source[lastIndex] = source[lastIndex], source[index]
	fmt.Println(source)
  return append(source[:index], source[index:lastIndex]...)
}

Thanks again for this helpful guide!

It does specifically mention that the trick work when ordering isn't important.

What I dislike about your version in that specific context of the book is that append is complex. It returns a value which could be a allocation. In this case, since the cap of the source will be large enough to accommodate the data, it won't, so the performance is the same. But either you explain all that in detail (which might not be an awful idea) or you just hand wave it away.

But your solution has the obvious benefit of being more generally suitable and probably a better choice for most people.

Glad the book has been helpful!