3 ms·
How do you mean exactly? Go has an iterable for map, slices, arrays, strings, channels with the "range"[0] keyword. The values returned by range are copies of
by kyrra 12y ago
How do you mean exactly? Go has an iterable for map, slices, arrays, strings, channels with the "range"[0] keyword. The values returned by range are copies of whatever is in the structure so they should be immune to mutation (unless you're messing with pointers).
[0] http://golang.org/ref/spec#RangeClause http://golang.org/ref/spec#RangeClause
- rakoo 12y agoHe means that what you actually want to do is modify some state outside of the loop when you're iterating, which means that your loop doesn't provide a "safe" context where you know what to expect. Are you sure you're modifying the correct outside variable ? Are you sure you really are modifying it: bar[i] = f(foo[i]) and not creating a new one: bar[i] := f(foo[i]) ? Are you sure you're not also modifying another variable that you didn't know was "linked" somehow ? Given the direction Go has taken, it would make very little sense to introduce functional programming bits. But you must admit that the immutability/lack of side effects of the FP gives you a lot of assurance on what to expect.
- kyrra 12y agoI think you need to provide an example of what you're trying to say, as the syntax you showed above is not valid. the := operator is for defining a new variable, not for creating a new instance of some type. The := operator is just shorthand. foo := 5 is shorthand for: var foo int foo = 5 the "range" keyword over an array gives you the index and the value at that index. If you don't need the index or the value, you can put a "_" in it's place (to save on the allocation). http://play.golang.org/p/Z2ejUlN5An http://play.golang.org/p/Z2ejUlN5An You'll notice that foo[i] is still printing "0", because range always creates a copy of the object assigned into v. Unless you start using pointers, you'll never have mutation issues.
- NateDad 12y agobar[i] := <anything> won't compile. You can only assign to slice/array indices.