notexOPENOverview
Notex/Languages/Code Review: for loops
02.13LESSON 13 OF 19 · 1 MIN READ

Code Review: for loops

Always free to read
  • 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.

Progress is saved on this device.
KEEP EXPLORING

One note leads to another.

Back to the library →
⌕
Search across the entire library ⌘ K