From c77c3b019606bdfd0e4dfa1e53ccbbd80e2f5a20 Mon Sep 17 00:00:00 2001
From: Rob Pike while and there is no do-while.
There are three forms, only one of which has semicolons:
-// Like a C for:
+// Like a C for
for init; condition; post { }
-// Like a C while:
+// Like a C while
for condition { }
// Like a C for(;;)
@@ -521,10 +521,29 @@ for key, value := range m { // key is unused; could call it '_'
}
+
+For strings, the range does more of the work for you, breaking out individual
+characters by parsing the UTF-8 (erroneous encodings consume one byte and produce the
+replacement rune U+FFFD). The loop
+
+for pos, char := range "æ¥æ¬èª" {
+ fmt.Printf("character %c starts at byte position %d\n", char, pos)
+}
+
++prints +
++character æ¥ starts at byte position 0 +character æ¬ starts at byte position 3 +character èª starts at byte position 6 ++
Finally, since Go has no comma operator and ++ and --
are statements not expressions, if you want to run multiple variables in a for
-you can use parallel assignment:
+you should use parallel assignment:
// Reverse a -- 2.52.0