Skip to content

Commit

Permalink
*Slice: don't mutate the underlying default value
Browse files Browse the repository at this point in the history
If the default value is present, we shouldn't mutate it. Appending slices
as the code was before mutates the underlying value:

package main

import (
	"fmt"
)

func main() {
	slice := []string{"a", "b", "c"}

	fmt.Println(append(slice[:1], slice[2:]...))
	fmt.Println(slice)
}
~ go run tester2.go
[a c]
[a c c]

Let's fix this by creating and returning an entirely new slice.

Closes #1169

Signed-off-by: Tycho Andersen <tycho@tycho.ws>
  • Loading branch information
tych0 committed Aug 5, 2020
1 parent 053ba9d commit 7c493f6
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 3 deletions.
4 changes: 3 additions & 1 deletion flag_int64_slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,9 @@ func lookupInt64Slice(name string, set *flag.FlagSet) []int64 {
func removeFromInt64Slice(slice []int64, val int64) []int64 {
for i, v := range slice {
if v == val {
return append(slice[:i], slice[i+1:]...)
ret := append([]int64{}, slice[:i]...)
ret = append(ret, slice[i+1:]...)
return ret
}
}
return slice
Expand Down
4 changes: 3 additions & 1 deletion flag_int_slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,9 @@ func lookupIntSlice(name string, set *flag.FlagSet) []int {
func removeFromIntSlice(slice []int, val int) []int {
for i, v := range slice {
if v == val {
return append(slice[:i], slice[i+1:]...)
ret := append([]int{}, slice[:i]...)
ret = append(ret, slice[i+1:]...)
return ret
}
}
return slice
Expand Down
4 changes: 3 additions & 1 deletion flag_string_slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,9 @@ func lookupStringSlice(name string, set *flag.FlagSet) []string {
func removeFromStringSlice(slice []string, val string) []string {
for i, v := range slice {
if v == val {
return append(slice[:i], slice[i+1:]...)
ret := append([]string{}, slice[:i]...)
ret = append(ret, slice[i+1:]...)
return ret
}
}
return slice
Expand Down

0 comments on commit 7c493f6

Please sign in to comment.