The most generalized version of the error that I could find looks like this:
package main
import "fmt"
func main() {
values := []any{1,2,3}
values = append(values[:1],values[1:])
fmt.Println(values)
}
Which causes a stack overflow (funny I'm posting on this site). If I remove values from the print statement and replace it with something else (such as 0), it doesn't throw an error and it prints properly.
If I use ... to use the append variadically, the code runs properly and prints [1 2 3].
I also tried putting fmt.Println("This section of code reached successfully!") between the change to values and the other print statement, but that prints before the error, which means that fmt.Println(values) is the line causing the overflow.
I can print the first item of values on its own without error, but printing the second item of the list on its own causes the overflow.
This version of the code runs without error:
package main
import "fmt"
func main() {
values := append([]any{1},[]any{2,3})
fmt.Println(values)
}
Why does this happen? This is a far more generalized version of an error I'm experiencing in one of my projects.
Slices are not arrays, they are views into arrays. Here is a simplified example, for illustration:
values := []any{1, 2, 3}
slice := values[1:] // [2, 3]
values[1] = 100
fmt.Println(slice) // [100, 3]
If you change an element of an array, the slice into it changes as well, and vice versa.
Now, when you append a slice of an array to that same array, you get into self-referential stuff.
values := []any{1,2,3}
values = append(values[:1],values[1:]) // [1, values[1:]]
values[1:] is [values[1:]] (because it is a live view into values, not [2, 3] as you assumed), which is [[values[1:]]]... so values is not [1, 2, 3], but [1, [[[[[[[[[[[[stackoverflow
Note that the structure itself is fine, though not what you want. It is only an error when you try to print it, since fmt.Println doesn't know how to handle a recursive structure.
In order to do what you want, you need to first copy the slice before you append it, so you don't end up adding to values a recursive reference into values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With