Yes. If you manipulate the meaning of the index (i) or the length of the slice, then do it explicitly:
for i := 0; i < len(a); i++ { if a[i] == 0 { //delete a[i]=a[0] a = a[1:] i-- } } For other methods, see https://go.dev/wiki/SliceTricks#filtering-without-allocating Shivansh Rustagi a következőt írta (2024. február 5., hétfő, 15:29:06 UTC+1): > Hi Guys, I had a question regarding: > > > On the other hand, if you have `for i, v := range a {` then the > > expression *is* evaluated before the start of the loop. > > I have a code (https://goplay.tools/snippet/dMwD0_rEhkB) where I am > ranging over a slice, and updating (removing the zeroth element form the > same slice being ranged over) here I see that the "i" values is not being > re-evaluated, it just gives an increasing number even if the ranged over > slice has changed . Which can also be seen when I am printing the ith > element given to me by the range, and the receiving out of range panic > > On Saturday, March 19, 2022 at 2:01:27 AM UTC+5:30 Dan Kortschak wrote: > >> On Fri, 2022-03-18 at 16:53 +0100, 'Axel Wagner' via golang-nuts wrote: >> > One thing to keep in mind is that Go development was incremental and >> > was done, from early on, by having multiple implementations. >> > Incremental processes often lead to different results than designing >> > a language from a blank slate. Ambiguities in the spec are often >> > discovered only when someone notices that implementations disagree >> > and must be resolved somehow. Sometimes that happens after Go 1 and >> > the resolution must happen in a way that, as much as possible, >> > retains stability guarantees. So, it's not unsurprising if we get >> > non-obvious spec clauses such as this. >> > >> > Specifically, I can well imagine that this particular case arose, >> > because it was discovered after the fact that one implementation >> > contained an optimization to not evaluate the argument to `len`, >> > while the other didn't and the question of side-effects only arose >> > when someone noticed. >> > >> > I don't really know the answer to your question. I can't think of >> > anything which would break. That being said, I also don't think it's >> > something that really needs "fixing", as it seems a pretty uncommon >> > concern. >> >> There is some discussion on the reasons when the original narrowing of >> the behaviour was introduced (https://codereview.appspot.com/4444050). >> >> It's actually quite an interesting spec change from a language history >> perspective, more because of the chan discussion than this particular >> issue. >> >> >> -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/237f0947-82e3-4467-834c-3c5fbfbb698dn%40googlegroups.com.