Thanks reply, I know *range expression is evaluated once before beginning the loop, *but I delete map in for statements also really affected the loop. why not set to nil can't affect real map.
func mapTest() { m := map[int]int{1: 1, 2: 2} for k, v := range m { println(k, v) delete(m, 2) // m = nil } } // output: // 1 1 On Tuesday, January 16, 2018 at 10:48:45 AM UTC+8, Kevin Powick wrote: > > > > On Monday, 15 January 2018 21:23:40 UTC-5, sheepbao wrote: >> >> I wrote this code, and why `map=nil` don't stop the loop? >> ```go >> >> func mapTest() { >> >> m := map[int]int{1: 1, 2: 2} >> >> for k, v := range m { >> >> println(k, v) >> >> m = nil >> >> } >> >> } >> >> ``` >> >> output: >> >> 1 1 >> >> 2 2 >> >> >> I don't understand when I set `m = nil`, the loop is not stop. m doesn't >> seem to be affected. >> > > https://golang.org/ref/spec#For_statements > > > *The range expression is evaluated once before beginning the loop, with > one exception: if the range expression is an array or a pointer to an array > and at most one iteration variable is present, only the range expression's > length is evaluated; if that length is constant, by definition the range > expression itself will not be evaluated. * > > > > -- > Kevin Powick > > > -- 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. For more options, visit https://groups.google.com/d/optout.