From 8aec612a80bfb2b935c3e228f6e9ea88758bdc70 Mon Sep 17 00:00:00 2001 From: Rob Pike Date: Wed, 2 Sep 2009 16:41:41 -0700 Subject: [PATCH] for loops comment out incomplete stuff R=rsc DELTA=61 (58 added, 0 deleted, 3 changed) OCL=34278 CL=34281 --- doc/effective_go.html | 62 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 60 insertions(+), 2 deletions(-) diff --git a/doc/effective_go.html b/doc/effective_go.html index b79f2a7a5c..740c1cf8e9 100644 --- a/doc/effective_go.html +++ b/doc/effective_go.html @@ -361,7 +361,7 @@ for one-line funcs and the like:

-func CopyInBackground(src, dst chan Item) {
+func CopyInBackground(dst, src chan Item) {
     go func() { for { dst <- <-src } }()
 }
 
@@ -385,7 +385,7 @@ case a > b:

-The grammar admits an empty statement after any statement list, which +The grammar accepts an empty statement after any statement list, which means a terminal semicolon is always OK. As a result, it's fine to put semicolons everywhere you'd put them in a C program—they would be fine after those return statements, @@ -480,6 +480,59 @@ codeUsing(f, d); +

For

+ +

+The Go for loop is similar to—but not the same as—C's. +It unifies for +and while and there is no do-while. +There are three forms, only one of which has semicolons: +

+
+// Like a C for:
+for init; condition; post { }
+
+// Like a C while:
+for condition { }
+
+// Like a C for(;;)
+for { }
+
+ +

+Short declarations make it easy to declare the index variable right in the loop: +

+
+sum := 0;
+for i := 0; i < 10; i++ {
+    sum += i
+}
+
+ +

+If you're looping over an array, slice, string, or map a range clause can set +it all up for you: +

+
+var m map[string] int;
+sum := 0;
+for key, value := range m {  // key is unused; could call it '_'
+    sum += value
+}
+
+ +

+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: +

+
+// Reverse a
+for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
+	a[i], a[j] = a[j], a[i]
+}
+
+

Switch

@@ -546,6 +599,9 @@ func Compare(a, b []byte) int { } +

More to come

+ + + -- 2.48.1