[...] Replace panics if s[i:j] is not a valid slice of s.
The following program doesn't panic, instead it returns a rather unexpected output:
func main() {
x := []int{10, 20, 30, 40}
y := []int{3, 4}
lo, hi := 2, 1
// fmt.Println(x[lo:hi]) this would panic with `panic: runtime error: slice bounds out of range [2:1]`
z := slices.Replace(x, lo, hi, y...)
fmt.Println(z)
}
A panic, because the slice expression x[2:1] is out of bounds as per the specs (and as per the Replace documentation):
For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range. For slices, the upper index bound is the slice capacity cap(a) rather than the length
What did you see instead?
The output of printing z is:
[10 20 3 4 20 30 40]
(unexpected outputs occur also in the general case when j - i != len(y))
Should probably just add bounds check like slices.Delete at the beginning of the function:
_ = s[i:j] // bounds check
The text was updated successfully, but these errors were encountered:
blackgreen100
changed the title
x/exp/slices: behavior of slices.Replace is inconsistent with subcli
x/exp/slices: behavior of slices.Replace is inconsistent with documentation
Nov 11, 2022
Despite the "Documentation" tag that gopherbot added, this just seems like a bug in that package.
blackgreen100
changed the title
x/exp/slices: behavior of slices.Replace is inconsistent with documentation
x/exp/slices: Replace doesn't panic with invalid indices
Nov 11, 2022
What version of Go are you using (
go version
)?Go 1.19
Does this issue reproduce with the latest release?
Yes, at tip
What did you do?
The documentation for
slices.Replace
states that:The following program doesn't panic, instead it returns a rather unexpected output:
https://go.dev/play/p/hCkCLy0YZnT?v=gotip
What did you expect to see?
A panic, because the slice expression
x[2:1]
is out of bounds as per the specs (and as per theReplace
documentation):What did you see instead?
The output of printing
z
is:(unexpected outputs occur also in the general case when
j - i != len(y)
)Should probably just add bounds check like
slices.Delete
at the beginning of the function:The text was updated successfully, but these errors were encountered: