s
and its type is []E
, where E
is the slice element type.
s[from:to]
and from <= to
.
copy
function
s = s[:from + copy(s[from:], s[to:])]
append
function
s = append(s[from:], s[to:]...)
slices.Delete
function (Since Go 1.21)
import "slices"
s = slices.Delete(s, from, to)
from < to
, the former two ways are as performant as each other.
from == to
, the first way is almost a no-op, but the second way is not.
slices.Delete
function was the same as the way 2. So it was also inefficient when from == to
. Since Go 1.22, the problem has been removed.
// The "clear" built-in function was introduced in Go 1.21.
clear(s[len(s):len(s)+to-from])
E
is zeroE
):
{
temp := s[len(s):len(s)+to-from]
for i := range temp {
temp[i] = zeroE
}
}
slices.Delete
function (with either of the above two manners). Since Go 1.22, the slices.Delete
function will automatically clear the freed-up elements.
The Go 101 project is hosted on Github. Welcome to improve Go 101 articles by submitting corrections for all kinds of mistakes, such as typos, grammar errors, wording inaccuracies, description flaws, code bugs and broken links.
If you would like to learn some Go details and facts every serveral days, please follow Go 101's official Twitter account @zigo_101.