-
Prefer for-range loops, especially when you’re iterating over every element in a compound type. They are also the easiest way to walk a string by runes or count up to a specified integer.
-
Go forbids unused declared variables, including loop variables. If you don’t need the first iteration variable in a range expression that returns two iteration variables, use the blank identifier _.
-
Never rely on map iteration order. It varies between runs by design.
-
Use range over function for alternate ways to iterate over slices, maps, and strings, or to iterate through user-defined container types.
-
Avoid deeply indented blocks. If possible, use break and continue to avoid deeply nested code within for loops.
-
Use labels with break or continue to exit or advance iteration of an outer loop when inside a nested one.
-
Never write a infinite for loop in production code. There must be some condition in the body that reaches a break or return. Real programs bound iteration and fail gracefully.
Code Review: for loops
Always free to read
Progress is saved on this device.