3 ms·
There is a new range syntax[1]. The release notes say it's rarely used, but makes code cleaner. In which cases would the syntax be useful? [1] https://golang.o
by valevk 12y ago
There is a new range syntax[1]. The release notes say it's rarely used, but makes code cleaner. In which cases would the syntax be useful?
[1] https://golang.org/doc/go1.4#forrange https://golang.org/doc/go1.4#forrange
- thomasahle 12y agoIf they added support for `range 10` to iterate 0-9 this would be useful for doing things a certain number of times. Now it's probably mostly useful for emptying iterators.
- andrewchambers 12y agoWhy do they need to add support for this? it already exists... https://github.com/bradfitz/iter/blob/master/iter.go https://github.com/bradfitz/iter/blob/master/iter.go
- thomasahle 12y agoI don't think that would be considered good Go code. It's no shorter than writing out the 3-part for loop, and it is probably slower.
- andrewchambers 12y agowhat extra operations do you think range on a slice would do? The generated assembly is probably the same. Stylistically it is odd however.
- deleted 12y ago[deleted]
- dsymonds 12y agoOne use case would be to exhaust a channel (that is, read everything off it until it is closed). Another might be to loop over something of a fixed size to correlate with a corresponding number of other things.
- Laremere 12y agoHere's a search of the go source for use of that: https://github.com/golang/go/search?p=3&q=%22for+range%22&type=Code&utf8=%E2%9C%93 https://github.com/golang/go/search?p=3&q=%22for+range%22&ty... Most of them are tests, but I see a couple genuine use cases: 1. Draining a channel until it closes. 2. Since range of a string gives utf8 runes, the RuneCountInString function in the utf8 package simply has an integer count, and does a range through the string increasing the count in every loop.
- rakoo 12y agoIt's useful if you want to schedule a function every x seconds: for range time.Tick(1 * time.Second) { fmt.Println("tick") }