mirror of
https://github.com/golang/go
synced 2024-11-25 01:57:56 -07:00
for loops
comment out incomplete stuff R=rsc DELTA=61 (58 added, 0 deleted, 3 changed) OCL=34278 CL=34281
This commit is contained in:
parent
dd7b583179
commit
8aec612a80
@ -361,7 +361,7 @@ for one-line <code>funcs</code> and the like:
|
||||
</p>
|
||||
|
||||
<pre>
|
||||
func CopyInBackground(src, dst chan Item) {
|
||||
func CopyInBackground(dst, src chan Item) {
|
||||
go func() { for { dst <- <-src } }()
|
||||
}
|
||||
</pre>
|
||||
@ -385,7 +385,7 @@ case a > b:
|
||||
</pre>
|
||||
|
||||
<p>
|
||||
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);
|
||||
</pre>
|
||||
|
||||
|
||||
<h3 id="for">For</h3>
|
||||
|
||||
<p>
|
||||
The Go <code>for</code> loop is similar to—but not the same as—C's.
|
||||
It unifies <code>for</code>
|
||||
and <code>while</code> and there is no <code>do-while</code>.
|
||||
There are three forms, only one of which has semicolons:
|
||||
</p>
|
||||
<pre>
|
||||
// Like a C for:
|
||||
for init; condition; post { }
|
||||
|
||||
// Like a C while:
|
||||
for condition { }
|
||||
|
||||
// Like a C for(;;)
|
||||
for { }
|
||||
</pre>
|
||||
|
||||
<p>
|
||||
Short declarations make it easy to declare the index variable right in the loop:
|
||||
</p>
|
||||
<pre>
|
||||
sum := 0;
|
||||
for i := 0; i < 10; i++ {
|
||||
sum += i
|
||||
}
|
||||
</pre>
|
||||
|
||||
<p>
|
||||
If you're looping over an array, slice, string, or map a <code>range</code> clause can set
|
||||
it all up for you:
|
||||
</p>
|
||||
<pre>
|
||||
var m map[string] int;
|
||||
sum := 0;
|
||||
for key, value := range m { // key is unused; could call it '_'
|
||||
sum += value
|
||||
}
|
||||
</pre>
|
||||
|
||||
<p>
|
||||
Finally, since Go has no comma operator and <code>++</code> and <code>--</code>
|
||||
are statements not expressions, if you want to run multiple variables in a <code>for</code>
|
||||
you can use parallel assignment:
|
||||
</p>
|
||||
<pre>
|
||||
// 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]
|
||||
}
|
||||
</pre>
|
||||
|
||||
<h3 id="switch">Switch</h3>
|
||||
|
||||
<p>
|
||||
@ -546,6 +599,9 @@ func Compare(a, b []byte) int {
|
||||
}
|
||||
</pre>
|
||||
|
||||
<h2>More to come</h2>
|
||||
|
||||
<!---
|
||||
<h2 id="functions">Functions</h2>
|
||||
|
||||
<h3 id="omit-wrappers">Omit needless wrappers</h3>
|
||||
@ -917,6 +973,8 @@ Consistency about little things
|
||||
lets readers concentrate on big ones.
|
||||
</p>
|
||||
|
||||
-->
|
||||
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
Loading…
Reference in New Issue
Block a user