Commit cd7062ef authored by Rob Pike's avatar Rob Pike

clean up the mess that copyright notices make

R=rsc
DELTA=555  (92 added, 38 deleted, 425 changed)
OCL=35691
CL=35693
parent cb1ad7e7
...@@ -32,14 +32,14 @@ cleanliness, blank lines remain blank. ...@@ -32,14 +32,14 @@ cleanliness, blank lines remain blank.
<p> <p>
Let's start in the usual way: Let's start in the usual way:
<p> <p>
<pre> <!-- progs/helloworld.go --> <pre> <!-- progs/helloworld.go /package/ END -->
01 package main 05 package main
<p> <p>
03 import fmt &quot;fmt&quot; // Package implementing formatted I/O. 07 import fmt &quot;fmt&quot; // Package implementing formatted I/O.
<p> <p>
05 func main() { 09 func main() {
06 fmt.Printf(&quot;Hello, world; or Καλημέρα κόσμε; or こんにちは 世界\n&quot;); 10 fmt.Printf(&quot;Hello, world; or Καλημέρα κόσμε; or こんにちは 世界\n&quot;);
07 } 11 }
</pre> </pre>
<p> <p>
Every Go source file declares, using a <code>package</code> statement, which package it's part of. Every Go source file declares, using a <code>package</code> statement, which package it's part of.
...@@ -67,42 +67,42 @@ Later we'll have much more to say about printing. ...@@ -67,42 +67,42 @@ Later we'll have much more to say about printing.
<p> <p>
Next up, here's a version of the Unix utility <code>echo(1)</code>: Next up, here's a version of the Unix utility <code>echo(1)</code>:
<p> <p>
<pre> <!-- progs/echo.go --> <pre> <!-- progs/echo.go /package/ END -->
01 package main 05 package main
<p> <p>
03 import ( 07 import (
04 &quot;os&quot;; 08 &quot;os&quot;;
05 &quot;flag&quot;; 09 &quot;flag&quot;;
06 ) 10 )
<p> <p>
08 var n_flag = flag.Bool(&quot;n&quot;, false, &quot;don't print final newline&quot;) 12 var n_flag = flag.Bool(&quot;n&quot;, false, &quot;don't print final newline&quot;)
<p> <p>
10 const ( 14 const (
11 kSpace = &quot; &quot;; 15 kSpace = &quot; &quot;;
12 kNewline = &quot;\n&quot;; 16 kNewline = &quot;\n&quot;;
13 ) 17 )
<p> <p>
15 func main() { 19 func main() {
16 flag.Parse(); // Scans the arg list and sets up flags 20 flag.Parse(); // Scans the arg list and sets up flags
17 var s string = &quot;&quot;; 21 var s string = &quot;&quot;;
18 for i := 0; i &lt; flag.NArg(); i++ { 22 for i := 0; i &lt; flag.NArg(); i++ {
19 if i &gt; 0 { 23 if i &gt; 0 {
20 s += kSpace 24 s += kSpace
21 } 25 }
22 s += flag.Arg(i) 26 s += flag.Arg(i)
23 } 27 }
24 if !*n_flag { 28 if !*n_flag {
25 s += kNewline 29 s += kNewline
26 } 30 }
27 os.Stdout.WriteString(s); 31 os.Stdout.WriteString(s);
28 } 32 }
</pre> </pre>
<p> <p>
This program is small but it's doing a number of new things. In the last example, This program is small but it's doing a number of new things. In the last example,
we saw <code>func</code> introducing a function. The keywords <code>var</code>, <code>const</code>, and <code>type</code> we saw <code>func</code> introducing a function. The keywords <code>var</code>, <code>const</code>, and <code>type</code>
(not used yet) also introduce declarations, as does <code>import</code>. (not used yet) also introduce declarations, as does <code>import</code>.
Notice that we can group declarations of the same sort into Notice that we can group declarations of the same sort into
parenthesized, semicolon-separated lists if we want, as on lines 3-6 and 10-13. parenthesized, semicolon-separated lists if we want, as on lines 4-10 and 14-17.
But it's not necessary to do so; we could have said But it's not necessary to do so; we could have said
<p> <p>
<pre> <pre>
...@@ -131,11 +131,11 @@ a naming conflict. ...@@ -131,11 +131,11 @@ a naming conflict.
<p> <p>
Given <code>os.Stdout</code> we can use its <code>WriteString</code> method to print the string. Given <code>os.Stdout</code> we can use its <code>WriteString</code> method to print the string.
<p> <p>
Having imported the <code>flag</code> package, line 8 creates a global variable to hold Having imported the <code>flag</code> package, line 12 creates a global variable to hold
the value of echo's <code>-n</code> flag. The variable <code>n_flag</code> has type <code>*bool</code>, pointer the value of echo's <code>-n</code> flag. The variable <code>n_flag</code> has type <code>*bool</code>, pointer
to <code>bool</code>. to <code>bool</code>.
<p> <p>
In <code>main.main</code>, we parse the arguments (line 16) and then create a local In <code>main.main</code>, we parse the arguments (line 20) and then create a local
string variable we will use to build the output. string variable we will use to build the output.
<p> <p>
The declaration statement has the form The declaration statement has the form
...@@ -169,7 +169,7 @@ the top level.) ...@@ -169,7 +169,7 @@ the top level.)
There's one in the <code>for</code> clause on the next line: There's one in the <code>for</code> clause on the next line:
<p> <p>
<pre> <!-- progs/echo.go /for/ --> <pre> <!-- progs/echo.go /for/ -->
18 for i := 0; i &lt; flag.NArg(); i++ { 22 for i := 0; i &lt; flag.NArg(); i++ {
</pre> </pre>
<p> <p>
The <code>flag</code> package has parsed the arguments and left the non-flag arguments The <code>flag</code> package has parsed the arguments and left the non-flag arguments
...@@ -214,11 +214,11 @@ of course you can change a string <i>variable</i> simply by ...@@ -214,11 +214,11 @@ of course you can change a string <i>variable</i> simply by
reassigning it. This snippet from <code>strings.go</code> is legal code: reassigning it. This snippet from <code>strings.go</code> is legal code:
<p> <p>
<pre> <!-- progs/strings.go /hello/ /ciao/ --> <pre> <!-- progs/strings.go /hello/ /ciao/ -->
07 s := &quot;hello&quot;; 11 s := &quot;hello&quot;;
08 if s[1] != 'e' { os.Exit(1) } 12 if s[1] != 'e' { os.Exit(1) }
09 s = &quot;good bye&quot;; 13 s = &quot;good bye&quot;;
10 var p *string = &amp;s; 14 var p *string = &amp;s;
11 *p = &quot;ciao&quot;; 15 *p = &quot;ciao&quot;;
</pre> </pre>
<p> <p>
However the following statements are illegal because they would modify However the following statements are illegal because they would modify
...@@ -273,19 +273,19 @@ create (efficiently) a slice reference and pass that. ...@@ -273,19 +273,19 @@ create (efficiently) a slice reference and pass that.
Using slices one can write this function (from <code>sum.go</code>): Using slices one can write this function (from <code>sum.go</code>):
<p> <p>
<pre> <!-- progs/sum.go /sum/ /^}/ --> <pre> <!-- progs/sum.go /sum/ /^}/ -->
05 func sum(a []int) int { // returns an int 09 func sum(a []int) int { // returns an int
06 s := 0; 10 s := 0;
07 for i := 0; i &lt; len(a); i++ { 11 for i := 0; i &lt; len(a); i++ {
08 s += a[i] 12 s += a[i]
09 } 13 }
10 return s 14 return s
11 } 15 }
</pre> </pre>
<p> <p>
and invoke it like this: and invoke it like this:
<p> <p>
<pre> <!-- progs/sum.go /1,2,3/ --> <pre> <!-- progs/sum.go /1,2,3/ -->
15 s := sum(&amp;[3]int{1,2,3}); // a slice of the array is passed to sum 19 s := sum(&amp;[3]int{1,2,3}); // a slice of the array is passed to sum
</pre> </pre>
<p> <p>
Note how the return type (<code>int</code>) is defined for <code>sum()</code> by stating it Note how the return type (<code>int</code>) is defined for <code>sum()</code> by stating it
...@@ -401,17 +401,17 @@ Next we'll look at a simple package for doing file I/O with the usual ...@@ -401,17 +401,17 @@ Next we'll look at a simple package for doing file I/O with the usual
sort of open/close/read/write interface. Here's the start of <code>file.go</code>: sort of open/close/read/write interface. Here's the start of <code>file.go</code>:
<p> <p>
<pre> <!-- progs/file.go /package/ /^}/ --> <pre> <!-- progs/file.go /package/ /^}/ -->
01 package file 05 package file
<p> <p>
03 import ( 07 import (
04 &quot;os&quot;; 08 &quot;os&quot;;
05 &quot;syscall&quot;; 09 &quot;syscall&quot;;
06 ) 10 )
<p> <p>
08 type File struct { 12 type File struct {
09 fd int; // file descriptor number 13 fd int; // file descriptor number
10 name string; // file name at Open time 14 name string; // file name at Open time
11 } 15 }
</pre> </pre>
<p> <p>
The first line declares the name of the package -- <code>file</code> -- The first line declares the name of the package -- <code>file</code> --
...@@ -442,12 +442,12 @@ will soon give it some exported, upper-case methods. ...@@ -442,12 +442,12 @@ will soon give it some exported, upper-case methods.
First, though, here is a factory to create them: First, though, here is a factory to create them:
<p> <p>
<pre> <!-- progs/file.go /newFile/ /^}/ --> <pre> <!-- progs/file.go /newFile/ /^}/ -->
13 func newFile(fd int, name string) *File { 17 func newFile(fd int, name string) *File {
14 if fd &lt; 0 { 18 if fd &lt; 0 {
15 return nil 19 return nil
16 } 20 }
17 return &amp;File{fd, name} 21 return &amp;File{fd, name}
18 } 22 }
</pre> </pre>
<p> <p>
This returns a pointer to a new <code>File</code> structure with the file descriptor and name This returns a pointer to a new <code>File</code> structure with the file descriptor and name
...@@ -463,29 +463,29 @@ object. We could write ...@@ -463,29 +463,29 @@ object. We could write
</pre> </pre>
but for simple structures like <code>File</code> it's easier to return the address of a nonce but for simple structures like <code>File</code> it's easier to return the address of a nonce
composite literal, as is done here on line 17. composite literal, as is done here on line 21.
<p> <p>
We can use the factory to construct some familiar, exported variables of type <code>*File</code>: We can use the factory to construct some familiar, exported variables of type <code>*File</code>:
<p> <p>
<pre> <!-- progs/file.go /var/ /^.$/ --> <pre> <!-- progs/file.go /var/ /^.$/ -->
20 var ( 24 var (
21 Stdin = newFile(0, &quot;/dev/stdin&quot;); 25 Stdin = newFile(0, &quot;/dev/stdin&quot;);
22 Stdout = newFile(1, &quot;/dev/stdout&quot;); 26 Stdout = newFile(1, &quot;/dev/stdout&quot;);
23 Stderr = newFile(2, &quot;/dev/stderr&quot;); 27 Stderr = newFile(2, &quot;/dev/stderr&quot;);
24 ) 28 )
</pre> </pre>
<p> <p>
The <code>newFile</code> function was not exported because it's internal. The proper, The <code>newFile</code> function was not exported because it's internal. The proper,
exported factory to use is <code>Open</code>: exported factory to use is <code>Open</code>:
<p> <p>
<pre> <!-- progs/file.go /func.Open/ /^}/ --> <pre> <!-- progs/file.go /func.Open/ /^}/ -->
26 func Open(name string, mode int, perm int) (file *File, err os.Error) { 30 func Open(name string, mode int, perm int) (file *File, err os.Error) {
27 r, e := syscall.Open(name, mode, perm); 31 r, e := syscall.Open(name, mode, perm);
28 if e != 0 { 32 if e != 0 {
29 err = os.Errno(e); 33 err = os.Errno(e);
30 } 34 }
31 return newFile(r, name), err 35 return newFile(r, name), err
32 } 36 }
</pre> </pre>
<p> <p>
There are a number of new things in these few lines. First, <code>Open</code> returns There are a number of new things in these few lines. First, <code>Open</code> returns
...@@ -495,9 +495,9 @@ multi-value return as a parenthesized list of declarations; syntactically ...@@ -495,9 +495,9 @@ multi-value return as a parenthesized list of declarations; syntactically
they look just like a second parameter list. The function they look just like a second parameter list. The function
<code>syscall.Open</code> <code>syscall.Open</code>
also has a multi-value return, which we can grab with the multi-variable also has a multi-value return, which we can grab with the multi-variable
declaration on line 27; it declares <code>r</code> and <code>e</code> to hold the two values, declaration on line 31; it declares <code>r</code> and <code>e</code> to hold the two values,
both of type <code>int64</code> (although you'd have to look at the <code>syscall</code> package both of type <code>int64</code> (although you'd have to look at the <code>syscall</code> package
to see that). Finally, line 28 returns two values: a pointer to the new <code>File</code> to see that). Finally, line 35 returns two values: a pointer to the new <code>File</code>
and the error. If <code>syscall.Open</code> fails, the file descriptor <code>r</code> will and the error. If <code>syscall.Open</code> fails, the file descriptor <code>r</code> will
be negative and <code>NewFile</code> will return <code>nil</code>. be negative and <code>NewFile</code> will return <code>nil</code>.
<p> <p>
...@@ -515,43 +515,43 @@ in parentheses before the function name. Here are some methods for <code>*File</ ...@@ -515,43 +515,43 @@ in parentheses before the function name. Here are some methods for <code>*File</
each of which declares a receiver variable <code>file</code>. each of which declares a receiver variable <code>file</code>.
<p> <p>
<pre> <!-- progs/file.go /Close/ END --> <pre> <!-- progs/file.go /Close/ END -->
34 func (file *File) Close() os.Error { 38 func (file *File) Close() os.Error {
35 if file == nil { 39 if file == nil {
36 return os.EINVAL 40 return os.EINVAL
37 } 41 }
38 e := syscall.Close(file.fd); 42 e := syscall.Close(file.fd);
39 file.fd = -1; // so it can't be closed again 43 file.fd = -1; // so it can't be closed again
40 if e != 0 { 44 if e != 0 {
41 return os.Errno(e); 45 return os.Errno(e);
42 } 46 }
43 return nil 47 return nil
44 } 48 }
<p> <p>
46 func (file *File) Read(b []byte) (ret int, err os.Error) { 50 func (file *File) Read(b []byte) (ret int, err os.Error) {
47 if file == nil { 51 if file == nil {
48 return -1, os.EINVAL 52 return -1, os.EINVAL
49 }
50 r, e := syscall.Read(file.fd, b);
51 if e != 0 {
52 err = os.Errno(e);
53 } 53 }
54 return int(r), err 54 r, e := syscall.Read(file.fd, b);
55 } 55 if e != 0 {
<p> 56 err = os.Errno(e);
57 func (file *File) Write(b []byte) (ret int, err os.Error) { 57 }
58 if file == nil { 58 return int(r), err
59 return -1, os.EINVAL 59 }
60 } <p>
61 r, e := syscall.Write(file.fd, b); 61 func (file *File) Write(b []byte) (ret int, err os.Error) {
62 if e != 0 { 62 if file == nil {
63 err = os.Errno(e); 63 return -1, os.EINVAL
64 } 64 }
65 return int(r), err 65 r, e := syscall.Write(file.fd, b);
66 } 66 if e != 0 {
<p> 67 err = os.Errno(e);
68 func (file *File) String() string { 68 }
69 return file.name 69 return int(r), err
70 } 70 }
<p>
72 func (file *File) String() string {
73 return file.name
74 }
</pre> </pre>
<p> <p>
There is no implicit <code>this</code> and the receiver variable must be used to access There is no implicit <code>this</code> and the receiver variable must be used to access
...@@ -569,24 +569,24 @@ set of such error values. ...@@ -569,24 +569,24 @@ set of such error values.
<p> <p>
We can now use our new package: We can now use our new package:
<p> <p>
<pre> <!-- progs/helloworld3.go --> <pre> <!-- progs/helloworld3.go /package/ END -->
01 package main 05 package main
<p> <p>
03 import ( 07 import (
04 &quot;./file&quot;; 08 &quot;./file&quot;;
05 &quot;fmt&quot;; 09 &quot;fmt&quot;;
06 &quot;os&quot;; 10 &quot;os&quot;;
07 ) 11 )
<p> <p>
09 func main() { 13 func main() {
10 hello := []byte{'h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '\n'}; 14 hello := []byte{'h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '\n'};
11 file.Stdout.Write(hello); 15 file.Stdout.Write(hello);
12 file, err := file.Open(&quot;/does/not/exist&quot;, 0, 0); 16 file, err := file.Open(&quot;/does/not/exist&quot;, 0, 0);
13 if file == nil { 17 if file == nil {
14 fmt.Printf(&quot;can't open file; err=%s\n&quot;, err.String()); 18 fmt.Printf(&quot;can't open file; err=%s\n&quot;, err.String());
15 os.Exit(1); 19 os.Exit(1);
16 } 20 }
17 } 21 }
</pre> </pre>
<p> <p>
The import of ''<code>./file</code>'' tells the compiler to use our own package rather than The import of ''<code>./file</code>'' tells the compiler to use our own package rather than
...@@ -606,55 +606,55 @@ Finally we can run the program: ...@@ -606,55 +606,55 @@ Finally we can run the program:
Building on the <code>file</code> package, here's a simple version of the Unix utility <code>cat(1)</code>, Building on the <code>file</code> package, here's a simple version of the Unix utility <code>cat(1)</code>,
<code>progs/cat.go</code>: <code>progs/cat.go</code>:
<p> <p>
<pre> <!-- progs/cat.go --> <pre> <!-- progs/cat.go /package/ END -->
01 package main 05 package main
<p> <p>
03 import ( 07 import (
04 &quot;./file&quot;; 08 &quot;./file&quot;;
05 &quot;flag&quot;; 09 &quot;flag&quot;;
06 &quot;fmt&quot;; 10 &quot;fmt&quot;;
07 &quot;os&quot;; 11 &quot;os&quot;;
08 ) 12 )
<p> <p>
10 func cat(f *file.File) { 14 func cat(f *file.File) {
11 const NBUF = 512; 15 const NBUF = 512;
12 var buf [NBUF]byte; 16 var buf [NBUF]byte;
13 for { 17 for {
14 switch nr, er := f.Read(&amp;buf); true { 18 switch nr, er := f.Read(&amp;buf); true {
15 case nr &lt; 0: 19 case nr &lt; 0:
16 fmt.Fprintf(os.Stderr, &quot;error reading from %s: %s\n&quot;, f.String(), er.String()); 20 fmt.Fprintf(os.Stderr, &quot;error reading from %s: %s\n&quot;, f.String(), er.String());
17 os.Exit(1); 21 os.Exit(1);
18 case nr == 0: // EOF 22 case nr == 0: // EOF
19 return; 23 return;
20 case nr &gt; 0: 24 case nr &gt; 0:
21 if nw, ew := file.Stdout.Write(buf[0:nr]); nw != nr { 25 if nw, ew := file.Stdout.Write(buf[0:nr]); nw != nr {
22 fmt.Fprintf(os.Stderr, &quot;error writing from %s: %s\n&quot;, f.String(), ew.String()); 26 fmt.Fprintf(os.Stderr, &quot;error writing from %s: %s\n&quot;, f.String(), ew.String());
23 } 27 }
24 } 28 }
25 } 29 }
26 } 30 }
<p> <p>
28 func main() { 32 func main() {
29 flag.Parse(); // Scans the arg list and sets up flags 33 flag.Parse(); // Scans the arg list and sets up flags
30 if flag.NArg() == 0 { 34 if flag.NArg() == 0 {
31 cat(file.Stdin); 35 cat(file.Stdin);
32 } 36 }
33 for i := 0; i &lt; flag.NArg(); i++ { 37 for i := 0; i &lt; flag.NArg(); i++ {
34 f, err := file.Open(flag.Arg(i), 0, 0); 38 f, err := file.Open(flag.Arg(i), 0, 0);
35 if f == nil { 39 if f == nil {
36 fmt.Fprintf(os.Stderr, &quot;can't open %s: error %s\n&quot;, flag.Arg(i), err); 40 fmt.Fprintf(os.Stderr, &quot;can't open %s: error %s\n&quot;, flag.Arg(i), err);
37 os.Exit(1); 41 os.Exit(1);
38 } 42 }
39 cat(f); 43 cat(f);
40 f.Close(); 44 f.Close();
41 } 45 }
42 } 46 }
</pre> </pre>
<p> <p>
By now this should be easy to follow, but the <code>switch</code> statement introduces some By now this should be easy to follow, but the <code>switch</code> statement introduces some
new features. Like a <code>for</code> loop, an <code>if</code> or <code>switch</code> can include an new features. Like a <code>for</code> loop, an <code>if</code> or <code>switch</code> can include an
initialization statement. The <code>switch</code> on line 14 uses one to create variables initialization statement. The <code>switch</code> on line 18 uses one to create variables
<code>nr</code> and <code>er</code> to hold the return values from <code>f.Read()</code>. (The <code>if</code> on line 21 <code>nr</code> and <code>er</code> to hold the return values from <code>f.Read()</code>. (The <code>if</code> on line 25
has the same idea.) The <code>switch</code> statement is general: it evaluates the cases has the same idea.) The <code>switch</code> statement is general: it evaluates the cases
from top to bottom looking for the first case that matches the value; the from top to bottom looking for the first case that matches the value; the
case expressions don't need to be constants or even integers, as long as case expressions don't need to be constants or even integers, as long as
...@@ -666,7 +666,7 @@ in a <code>for</code> statement, a missing value means <code>true</code>. In fa ...@@ -666,7 +666,7 @@ in a <code>for</code> statement, a missing value means <code>true</code>. In fa
is a form of <code>if-else</code> chain. While we're here, it should be mentioned that in is a form of <code>if-else</code> chain. While we're here, it should be mentioned that in
<code>switch</code> statements each <code>case</code> has an implicit <code>break</code>. <code>switch</code> statements each <code>case</code> has an implicit <code>break</code>.
<p> <p>
Line 21 calls <code>Write()</code> by slicing the incoming buffer, which is itself a slice. Line 25 calls <code>Write()</code> by slicing the incoming buffer, which is itself a slice.
Slices provide the standard Go way to handle I/O buffers. Slices provide the standard Go way to handle I/O buffers.
<p> <p>
Now let's make a variant of <code>cat</code> that optionally does <code>rot13</code> on its input. Now let's make a variant of <code>cat</code> that optionally does <code>rot13</code> on its input.
...@@ -678,10 +678,10 @@ so let's start by defining an interface that has exactly those two methods. ...@@ -678,10 +678,10 @@ so let's start by defining an interface that has exactly those two methods.
Here is code from <code>progs/cat_rot13.go</code>: Here is code from <code>progs/cat_rot13.go</code>:
<p> <p>
<pre> <!-- progs/cat_rot13.go /type.reader/ /^}/ --> <pre> <!-- progs/cat_rot13.go /type.reader/ /^}/ -->
22 type reader interface { 26 type reader interface {
23 Read(b []byte) (ret int, err os.Error); 27 Read(b []byte) (ret int, err os.Error);
24 String() string; 28 String() string;
25 } 29 }
</pre> </pre>
<p> <p>
Any type that implements the two methods of <code>reader</code> -- regardless of whatever Any type that implements the two methods of <code>reader</code> -- regardless of whatever
...@@ -695,66 +695,66 @@ the type and implement the methods and with no other bookkeeping, ...@@ -695,66 +695,66 @@ the type and implement the methods and with no other bookkeeping,
we have a second implementation of the <code>reader</code> interface. we have a second implementation of the <code>reader</code> interface.
<p> <p>
<pre> <!-- progs/cat_rot13.go /type.rotate13/ /end.of.rotate13/ --> <pre> <!-- progs/cat_rot13.go /type.rotate13/ /end.of.rotate13/ -->
27 type rotate13 struct { 31 type rotate13 struct {
28 source reader; 32 source reader;
29 }
<p>
31 func newRotate13(source reader) *rotate13 {
32 return &amp;rotate13{source}
33 } 33 }
<p> <p>
35 func (r13 *rotate13) Read(b []byte) (ret int, err os.Error) { 35 func newRotate13(source reader) *rotate13 {
36 r, e := r13.source.Read(b); 36 return &amp;rotate13{source}
37 for i := 0; i &lt; r; i++ { 37 }
38 b[i] = rot13(b[i])
39 }
40 return r, e
41 }
<p> <p>
43 func (r13 *rotate13) String() string { 39 func (r13 *rotate13) Read(b []byte) (ret int, err os.Error) {
44 return r13.source.String() 40 r, e := r13.source.Read(b);
41 for i := 0; i &lt; r; i++ {
42 b[i] = rot13(b[i])
43 }
44 return r, e
45 } 45 }
46 // end of rotate13 implementation <p>
47 func (r13 *rotate13) String() string {
48 return r13.source.String()
49 }
50 // end of rotate13 implementation
</pre> </pre>
<p> <p>
(The <code>rot13</code> function called on line 38 is trivial and not worth reproducing.) (The <code>rot13</code> function called on line 42 is trivial and not worth reproducing.)
<p> <p>
To use the new feature, we define a flag: To use the new feature, we define a flag:
<p> <p>
<pre> <!-- progs/cat_rot13.go /rot13_flag/ --> <pre> <!-- progs/cat_rot13.go /rot13_flag/ -->
10 var rot13_flag = flag.Bool(&quot;rot13&quot;, false, &quot;rot13 the input&quot;) 14 var rot13_flag = flag.Bool(&quot;rot13&quot;, false, &quot;rot13 the input&quot;)
</pre> </pre>
<p> <p>
and use it from within a mostly unchanged <code>cat()</code> function: and use it from within a mostly unchanged <code>cat()</code> function:
<p> <p>
<pre> <!-- progs/cat_rot13.go /func.cat/ /^}/ --> <pre> <!-- progs/cat_rot13.go /func.cat/ /^}/ -->
48 func cat(r reader) { 52 func cat(r reader) {
49 const NBUF = 512; 53 const NBUF = 512;
50 var buf [NBUF]byte; 54 var buf [NBUF]byte;
<p> <p>
52 if *rot13_flag { 56 if *rot13_flag {
53 r = newRotate13(r) 57 r = newRotate13(r)
54 } 58 }
55 for { 59 for {
56 switch nr, er := r.Read(&amp;buf); { 60 switch nr, er := r.Read(&amp;buf); {
57 case nr &lt; 0: 61 case nr &lt; 0:
58 fmt.Fprintf(os.Stderr, &quot;error reading from %s: %s\n&quot;, r.String(), er.String()); 62 fmt.Fprintf(os.Stderr, &quot;error reading from %s: %s\n&quot;, r.String(), er.String());
59 os.Exit(1); 63 os.Exit(1);
60 case nr == 0: // EOF 64 case nr == 0: // EOF
61 return; 65 return;
62 case nr &gt; 0: 66 case nr &gt; 0:
63 nw, ew := file.Stdout.Write(buf[0:nr]); 67 nw, ew := file.Stdout.Write(buf[0:nr]);
64 if nw != nr { 68 if nw != nr {
65 fmt.Fprintf(os.Stderr, &quot;error writing from %s: %s\n&quot;, r.String(), ew.String()); 69 fmt.Fprintf(os.Stderr, &quot;error writing from %s: %s\n&quot;, r.String(), ew.String());
66 } 70 }
67 } 71 }
68 } 72 }
69 } 73 }
</pre> </pre>
<p> <p>
(We could also do the wrapping in <code>main</code> and leave <code>cat()</code> mostly alone, except (We could also do the wrapping in <code>main</code> and leave <code>cat()</code> mostly alone, except
for changing the type of the argument; consider that an exercise.) for changing the type of the argument; consider that an exercise.)
Lines 52 through 55 set it all up: If the <code>rot13</code> flag is true, wrap the <code>reader</code> Lines 56 through 59 set it all up: If the <code>rot13</code> flag is true, wrap the <code>reader</code>
we received into a <code>rotate13</code> and proceed. Note that the interface variables we received into a <code>rotate13</code> and proceed. Note that the interface variables
are values, not pointers: the argument is of type <code>reader</code>, not <code>*reader</code>, are values, not pointers: the argument is of type <code>reader</code>, not <code>*reader</code>,
even though under the covers it holds a pointer to a <code>struct</code>. even though under the covers it holds a pointer to a <code>struct</code>.
...@@ -798,61 +798,35 @@ same interface variable. ...@@ -798,61 +798,35 @@ same interface variable.
As an example, consider this simple sort algorithm taken from <code>progs/sort.go</code>: As an example, consider this simple sort algorithm taken from <code>progs/sort.go</code>:
<p> <p>
<pre> <!-- progs/sort.go /func.Sort/ /^}/ --> <pre> <!-- progs/sort.go /func.Sort/ /^}/ -->
09 func Sort(data Interface) { 13 func Sort(data Interface) {
10 for i := 1; i &lt; data.Len(); i++ { 14 for i := 1; i &lt; data.Len(); i++ {
11 for j := i; j &gt; 0 &amp;&amp; data.Less(j, j-1); j-- { 15 for j := i; j &gt; 0 &amp;&amp; data.Less(j, j-1); j-- {
12 data.Swap(j, j-1); 16 data.Swap(j, j-1);
13 } 17 }
14 } 18 }
15 } 19 }
</pre> </pre>
<p> <p>
The code needs only three methods, which we wrap into sort's <code>Interface</code>: The code needs only three methods, which we wrap into sort's <code>Interface</code>:
<p> <p>
<pre> <!-- progs/sort.go /interface/ /^}/ --> <pre> <!-- progs/sort.go /interface/ /^}/ -->
03 type Interface interface { 07 type Interface interface {
04 Len() int; 08 Len() int;
05 Less(i, j int) bool; 09 Less(i, j int) bool;
06 Swap(i, j int); 10 Swap(i, j int);
07 } 11 }
</pre> </pre>
<p> <p>
We can apply <code>Sort</code> to any type that implements <code>Len</code>, <code>Less</code>, and <code>Swap</code>. We can apply <code>Sort</code> to any type that implements <code>Len</code>, <code>Less</code>, and <code>Swap</code>.
The <code>sort</code> package includes the necessary methods to allow sorting of The <code>sort</code> package includes the necessary methods to allow sorting of
arrays of integers, strings, etc.; here's the code for arrays of <code>int</code> arrays of integers, strings, etc.; here's the code for arrays of <code>int</code>
<p> <p>
<pre> <!-- progs/sort.go /type.*IntArray/ /swap/ --> <pre> <!-- progs/sort.go /type.*IntArray/ /Swap/ -->
29 type IntArray []int 33 type IntArray []int
<p>
31 func (p IntArray) Len() int { return len(p); }
32 func (p IntArray) Less(i, j int) bool { return p[i] &lt; p[j]; }
33 func (p IntArray) Swap(i, j int) { p[i], p[j] = p[j], p[i]; }
<p>
<p>
36 type FloatArray []float
<p>
38 func (p FloatArray) Len() int { return len(p); }
39 func (p FloatArray) Less(i, j int) bool { return p[i] &lt; p[j]; }
40 func (p FloatArray) Swap(i, j int) { p[i], p[j] = p[j], p[i]; }
<p>
<p>
43 type StringArray []string
<p>
45 func (p StringArray) Len() int { return len(p); }
46 func (p StringArray) Less(i, j int) bool { return p[i] &lt; p[j]; }
47 func (p StringArray) Swap(i, j int) { p[i], p[j] = p[j], p[i]; }
<p>
<p>
50 // Convenience wrappers for common cases
<p>
52 func SortInts(a []int) { Sort(IntArray(a)); }
53 func SortFloats(a []float) { Sort(FloatArray(a)); }
54 func SortStrings(a []string) { Sort(StringArray(a)); }
<p>
<p> <p>
57 func IntsAreSorted(a []int) bool { return IsSorted(IntArray(a)); } 35 func (p IntArray) Len() int { return len(p); }
58 func FloatsAreSorted(a []float) bool { return IsSorted(FloatArray(a)); } 36 func (p IntArray) Less(i, j int) bool { return p[i] &lt; p[j]; }
59 func StringsAreSorted(a []string) bool { return IsSorted(StringArray(a)); } 37 func (p IntArray) Swap(i, j int) { p[i], p[j] = p[j], p[i]; }
</pre> </pre>
<p> <p>
Here we see methods defined for non-<code>struct</code> types. You can define methods Here we see methods defined for non-<code>struct</code> types. You can define methods
...@@ -863,33 +837,33 @@ uses a function in the <code>sort</code> package, omitted here for brevity, ...@@ -863,33 +837,33 @@ uses a function in the <code>sort</code> package, omitted here for brevity,
to test that the result is sorted. to test that the result is sorted.
<p> <p>
<pre> <!-- progs/sortmain.go /func.ints/ /^}/ --> <pre> <!-- progs/sortmain.go /func.ints/ /^}/ -->
08 func ints() { 12 func ints() {
09 data := []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586}; 13 data := []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586};
10 a := sort.IntArray(data); 14 a := sort.IntArray(data);
11 sort.Sort(a); 15 sort.Sort(a);
12 if !sort.IsSorted(a) { 16 if !sort.IsSorted(a) {
13 panic() 17 panic()
14 } 18 }
15 } 19 }
</pre> </pre>
<p> <p>
If we have a new type we want to be able to sort, all we need to do is If we have a new type we want to be able to sort, all we need to do is
to implement the three methods for that type, like this: to implement the three methods for that type, like this:
<p> <p>
<pre> <!-- progs/sortmain.go /type.day/ /Swap/ --> <pre> <!-- progs/sortmain.go /type.day/ /Swap/ -->
26 type day struct { 30 type day struct {
27 num int; 31 num int;
28 short_name string; 32 short_name string;
29 long_name string; 33 long_name string;
30 }
<p>
32 type dayArray struct {
33 data []*day;
34 } 34 }
<p> <p>
36 func (p *dayArray) Len() int { return len(p.data); } 36 type dayArray struct {
37 func (p *dayArray) Less(i, j int) bool { return p.data[i].num &lt; p.data[j].num; } 37 data []*day;
38 func (p *dayArray) Swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i]; } 38 }
<p>
40 func (p *dayArray) Len() int { return len(p.data); }
41 func (p *dayArray) Less(i, j int) bool { return p.data[i].num &lt; p.data[j].num; }
42 func (p *dayArray) Swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i]; }
</pre> </pre>
<p> <p>
<p> <p>
...@@ -920,8 +894,8 @@ can just say <code>%d</code>; <code>Printf</code> knows the size and signedness ...@@ -920,8 +894,8 @@ can just say <code>%d</code>; <code>Printf</code> knows the size and signedness
integer and can do the right thing for you. The snippet integer and can do the right thing for you. The snippet
<p> <p>
<pre> <!-- progs/print.go NR==6 NR==7 --> <pre> <!-- progs/print.go NR==6 NR==7 -->
06 var u64 uint64 = 1&lt;&lt;64-1; 06
07 fmt.Printf(&quot;%d %d\n&quot;, u64, int64(u64)); 07 import &quot;fmt&quot;
</pre> </pre>
<p> <p>
prints prints
...@@ -934,10 +908,10 @@ In fact, if you're lazy the format <code>%v</code> will print, in a simple ...@@ -934,10 +908,10 @@ In fact, if you're lazy the format <code>%v</code> will print, in a simple
appropriate style, any value, even an array or structure. The output of appropriate style, any value, even an array or structure. The output of
<p> <p>
<pre> <!-- progs/print.go NR==10 NR==13 --> <pre> <!-- progs/print.go NR==10 NR==13 -->
10 type T struct { a int; b string }; 10 var u64 uint64 = 1&lt;&lt;64-1;
11 t := T{77, &quot;Sunset Strip&quot;}; 11 fmt.Printf(&quot;%d %d\n&quot;, u64, int64(u64));
12 a := []int{1, 2, 3, 4}; <p>
13 fmt.Printf(&quot;%v %v %v\n&quot;, u64, t, a); 13 // harder stuff
</pre> </pre>
<p> <p>
is is
...@@ -954,8 +928,8 @@ and adds a newline. The output of each of these two lines is identical ...@@ -954,8 +928,8 @@ and adds a newline. The output of each of these two lines is identical
to that of the <code>Printf</code> call above. to that of the <code>Printf</code> call above.
<p> <p>
<pre> <!-- progs/print.go NR==14 NR==15 --> <pre> <!-- progs/print.go NR==14 NR==15 -->
14 fmt.Print(u64, &quot; &quot;, t, &quot; &quot;, a, &quot;\n&quot;); 14 type T struct { a int; b string };
15 fmt.Println(u64, t, a); 15 t := T{77, &quot;Sunset Strip&quot;};
</pre> </pre>
<p> <p>
If you have your own type you'd like <code>Printf</code> or <code>Print</code> to format, If you have your own type you'd like <code>Printf</code> or <code>Print</code> to format,
...@@ -965,16 +939,20 @@ the method and if so, use it rather than some other formatting. ...@@ -965,16 +939,20 @@ the method and if so, use it rather than some other formatting.
Here's a simple example. Here's a simple example.
<p> <p>
<pre> <!-- progs/print_string.go NR==5 END --> <pre> <!-- progs/print_string.go NR==5 END -->
05 type testType struct { a int; b string } 05 package main
<p> <p>
07 func (t *testType) String() string { 07 import &quot;fmt&quot;
08 return fmt.Sprint(t.a) + &quot; &quot; + t.b
09 }
<p> <p>
11 func main() { 09 type testType struct { a int; b string }
12 t := &amp;testType{77, &quot;Sunset Strip&quot;}; <p>
13 fmt.Println(t) 11 func (t *testType) String() string {
14 } 12 return fmt.Sprint(t.a) + &quot; &quot; + t.b
13 }
<p>
15 func main() {
16 t := &amp;testType{77, &quot;Sunset Strip&quot;};
17 fmt.Println(t)
18 }
</pre> </pre>
<p> <p>
Since <code>*T</code> has a <code>String()</code> method, the Since <code>*T</code> has a <code>String()</code> method, the
...@@ -1076,12 +1054,12 @@ coordinates the communication; as with maps and slices, use ...@@ -1076,12 +1054,12 @@ coordinates the communication; as with maps and slices, use
Here is the first function in <code>progs/sieve.go</code>: Here is the first function in <code>progs/sieve.go</code>:
<p> <p>
<pre> <!-- progs/sieve.go /Send/ /^}/ --> <pre> <!-- progs/sieve.go /Send/ /^}/ -->
05 // Send the sequence 2, 3, 4, ... to channel 'ch'. 09 // Send the sequence 2, 3, 4, ... to channel 'ch'.
06 func generate(ch chan int) { 10 func generate(ch chan int) {
07 for i := 2; ; i++ { 11 for i := 2; ; i++ {
08 ch &lt;- i // Send 'i' to channel 'ch'. 12 ch &lt;- i // Send 'i' to channel 'ch'.
09 } 13 }
10 } 14 }
</pre> </pre>
<p> <p>
The <code>generate</code> function sends the sequence 2, 3, 4, 5, ... to its The <code>generate</code> function sends the sequence 2, 3, 4, 5, ... to its
...@@ -1094,17 +1072,17 @@ channel, and a prime number. It copies values from the input to the ...@@ -1094,17 +1072,17 @@ channel, and a prime number. It copies values from the input to the
output, discarding anything divisible by the prime. The unary communications output, discarding anything divisible by the prime. The unary communications
operator <code>&lt;-</code> (receive) retrieves the next value on the channel. operator <code>&lt;-</code> (receive) retrieves the next value on the channel.
<p> <p>
<pre> <!-- progs/sieve.go /Copy/ /^}/ --> <pre> <!-- progs/sieve.go /Copy.the/ /^}/ -->
12 // Copy the values from channel 'in' to channel 'out', 16 // Copy the values from channel 'in' to channel 'out',
13 // removing those divisible by 'prime'. 17 // removing those divisible by 'prime'.
14 func filter(in, out chan int, prime int) { 18 func filter(in, out chan int, prime int) {
15 for { 19 for {
16 i := &lt;-in; // Receive value of new variable 'i' from 'in'. 20 i := &lt;-in; // Receive value of new variable 'i' from 'in'.
17 if i % prime != 0 { 21 if i % prime != 0 {
18 out &lt;- i // Send 'i' to channel 'out'. 22 out &lt;- i // Send 'i' to channel 'out'.
19 } 23 }
20 } 24 }
21 } 25 }
</pre> </pre>
<p> <p>
The generator and filters execute concurrently. Go has The generator and filters execute concurrently. Go has
...@@ -1133,20 +1111,20 @@ Back to our prime sieve. Here's how the sieve pipeline is stitched ...@@ -1133,20 +1111,20 @@ Back to our prime sieve. Here's how the sieve pipeline is stitched
together: together:
<p> <p>
<pre> <!-- progs/sieve.go /func.main/ /^}/ --> <pre> <!-- progs/sieve.go /func.main/ /^}/ -->
24 func main() { 28 func main() {
25 ch := make(chan int); // Create a new channel. 29 ch := make(chan int); // Create a new channel.
26 go generate(ch); // Start generate() as a goroutine. 30 go generate(ch); // Start generate() as a goroutine.
27 for { 31 for {
28 prime := &lt;-ch; 32 prime := &lt;-ch;
29 fmt.Println(prime); 33 fmt.Println(prime);
30 ch1 := make(chan int); 34 ch1 := make(chan int);
31 go filter(ch, ch1, prime); 35 go filter(ch, ch1, prime);
32 ch = ch1 36 ch = ch1
33 } 37 }
34 } 38 }
</pre> </pre>
<p> <p>
Line 25 creates the initial channel to pass to <code>generate</code>, which it Line 29 creates the initial channel to pass to <code>generate</code>, which it
then starts up. As each prime pops out of the channel, a new <code>filter</code> then starts up. As each prime pops out of the channel, a new <code>filter</code>
is added to the pipeline and <i>its</i> output becomes the new value is added to the pipeline and <i>its</i> output becomes the new value
of <code>ch</code>. of <code>ch</code>.
...@@ -1156,15 +1134,15 @@ in this style of programming. Here is a variant version ...@@ -1156,15 +1134,15 @@ in this style of programming. Here is a variant version
of <code>generate</code>, from <code>progs/sieve1.go</code>: of <code>generate</code>, from <code>progs/sieve1.go</code>:
<p> <p>
<pre> <!-- progs/sieve1.go /func.generate/ /^}/ --> <pre> <!-- progs/sieve1.go /func.generate/ /^}/ -->
06 func generate() chan int { 10 func generate() chan int {
07 ch := make(chan int); 11 ch := make(chan int);
08 go func(){ 12 go func(){
09 for i := 2; ; i++ { 13 for i := 2; ; i++ {
10 ch &lt;- i 14 ch &lt;- i
11 } 15 }
12 }(); 16 }();
13 return ch; 17 return ch;
14 } 18 }
</pre> </pre>
<p> <p>
This version does all the setup internally. It creates the output This version does all the setup internally. It creates the output
...@@ -1172,7 +1150,7 @@ channel, launches a goroutine internally using a function literal, and ...@@ -1172,7 +1150,7 @@ channel, launches a goroutine internally using a function literal, and
returns the channel to the caller. It is a factory for concurrent returns the channel to the caller. It is a factory for concurrent
execution, starting the goroutine and returning its connection. execution, starting the goroutine and returning its connection.
<p> <p>
The function literal notation (lines 8-12) allows us to construct an The function literal notation (lines 12-16) allows us to construct an
anonymous function and invoke it on the spot. Notice that the local anonymous function and invoke it on the spot. Notice that the local
variable <code>ch</code> is available to the function literal and lives on even variable <code>ch</code> is available to the function literal and lives on even
after <code>generate</code> returns. after <code>generate</code> returns.
...@@ -1180,46 +1158,46 @@ after <code>generate</code> returns. ...@@ -1180,46 +1158,46 @@ after <code>generate</code> returns.
The same change can be made to <code>filter</code>: The same change can be made to <code>filter</code>:
<p> <p>
<pre> <!-- progs/sieve1.go /func.filter/ /^}/ --> <pre> <!-- progs/sieve1.go /func.filter/ /^}/ -->
17 func filter(in chan int, prime int) chan int { 21 func filter(in chan int, prime int) chan int {
18 out := make(chan int); 22 out := make(chan int);
19 go func() { 23 go func() {
20 for { 24 for {
21 if i := &lt;-in; i % prime != 0 { 25 if i := &lt;-in; i % prime != 0 {
22 out &lt;- i 26 out &lt;- i
23 } 27 }
24 } 28 }
25 }(); 29 }();
26 return out; 30 return out;
27 } 31 }
</pre> </pre>
<p> <p>
The <code>sieve</code> function's main loop becomes simpler and clearer as a The <code>sieve</code> function's main loop becomes simpler and clearer as a
result, and while we're at it let's turn it into a factory too: result, and while we're at it let's turn it into a factory too:
<p> <p>
<pre> <!-- progs/sieve1.go /func.sieve/ /^}/ --> <pre> <!-- progs/sieve1.go /func.sieve/ /^}/ -->
29 func sieve() chan int { 33 func sieve() chan int {
30 out := make(chan int); 34 out := make(chan int);
31 go func() { 35 go func() {
32 ch := generate(); 36 ch := generate();
33 for { 37 for {
34 prime := &lt;-ch; 38 prime := &lt;-ch;
35 out &lt;- prime; 39 out &lt;- prime;
36 ch = filter(ch, prime); 40 ch = filter(ch, prime);
37 } 41 }
38 }(); 42 }();
39 return out; 43 return out;
40 } 44 }
</pre> </pre>
<p> <p>
Now <code>main</code>'s interface to the prime sieve is a channel of primes: Now <code>main</code>'s interface to the prime sieve is a channel of primes:
<p> <p>
<pre> <!-- progs/sieve1.go /func.main/ /^}/ --> <pre> <!-- progs/sieve1.go /func.main/ /^}/ -->
42 func main() { 46 func main() {
43 primes := sieve(); 47 primes := sieve();
44 for { 48 for {
45 fmt.Println(&lt;-primes); 49 fmt.Println(&lt;-primes);
46 } 50 }
47 } 51 }
</pre> </pre>
<p> <p>
<h2>Multiplexing</h2> <h2>Multiplexing</h2>
...@@ -1232,48 +1210,48 @@ to illustrate the idea. It starts by defining a <code>request</code> type, whic ...@@ -1232,48 +1210,48 @@ to illustrate the idea. It starts by defining a <code>request</code> type, whic
that will be used for the reply. that will be used for the reply.
<p> <p>
<pre> <!-- progs/server.go /type.request/ /^}/ --> <pre> <!-- progs/server.go /type.request/ /^}/ -->
05 type request struct { 09 type request struct {
06 a, b int; 10 a, b int;
07 replyc chan int; 11 replyc chan int;
08 } 12 }
</pre> </pre>
<p> <p>
The server will be trivial: it will do simple binary operations on integers. Here's the The server will be trivial: it will do simple binary operations on integers. Here's the
code that invokes the operation and responds to the request: code that invokes the operation and responds to the request:
<p> <p>
<pre> <!-- progs/server.go /type.binOp/ /^}/ --> <pre> <!-- progs/server.go /type.binOp/ /^}/ -->
10 type binOp func(a, b int) int 14 type binOp func(a, b int) int
<p> <p>
12 func run(op binOp, req *request) { 16 func run(op binOp, req *request) {
13 reply := op(req.a, req.b); 17 reply := op(req.a, req.b);
14 req.replyc &lt;- reply; 18 req.replyc &lt;- reply;
15 } 19 }
</pre> </pre>
<p> <p>
Line 10 defines the name <code>binOp</code> to be a function taking two integers and Line 18 defines the name <code>binOp</code> to be a function taking two integers and
returning a third. returning a third.
<p> <p>
The <code>server</code> routine loops forever, receiving requests and, to avoid blocking due to The <code>server</code> routine loops forever, receiving requests and, to avoid blocking due to
a long-running operation, starting a goroutine to do the actual work. a long-running operation, starting a goroutine to do the actual work.
<p> <p>
<pre> <!-- progs/server.go /func.server/ /^}/ --> <pre> <!-- progs/server.go /func.server/ /^}/ -->
17 func server(op binOp, service chan *request) { 21 func server(op binOp, service chan *request) {
18 for { 22 for {
19 req := &lt;-service; 23 req := &lt;-service;
20 go run(op, req); // don't wait for it 24 go run(op, req); // don't wait for it
21 } 25 }
22 } 26 }
</pre> </pre>
<p> <p>
We construct a server in a familiar way, starting it up and returning a channel to We construct a server in a familiar way, starting it up and returning a channel to
connect to it: connect to it:
<p> <p>
<pre> <!-- progs/server.go /func.startServer/ /^}/ --> <pre> <!-- progs/server.go /func.startServer/ /^}/ -->
24 func startServer(op binOp) chan *request { 28 func startServer(op binOp) chan *request {
25 req := make(chan *request); 29 req := make(chan *request);
26 go server(op, req); 30 go server(op, req);
27 return req; 31 return req;
28 } 32 }
</pre> </pre>
<p> <p>
Here's a simple test. It starts a server with an addition operator, and sends out Here's a simple test. It starts a server with an addition operator, and sends out
...@@ -1281,24 +1259,24 @@ lots of requests but doesn't wait for the reply. Only after all the requests ar ...@@ -1281,24 +1259,24 @@ lots of requests but doesn't wait for the reply. Only after all the requests ar
does it check the results. does it check the results.
<p> <p>
<pre> <!-- progs/server.go /func.main/ /^}/ --> <pre> <!-- progs/server.go /func.main/ /^}/ -->
30 func main() { 34 func main() {
31 adder := startServer(func(a, b int) int { return a + b }); 35 adder := startServer(func(a, b int) int { return a + b });
32 const N = 100; 36 const N = 100;
33 var reqs [N]request; 37 var reqs [N]request;
34 for i := 0; i &lt; N; i++ { 38 for i := 0; i &lt; N; i++ {
35 req := &amp;reqs[i]; 39 req := &amp;reqs[i];
36 req.a = i; 40 req.a = i;
37 req.b = i + N; 41 req.b = i + N;
38 req.replyc = make(chan int); 42 req.replyc = make(chan int);
39 adder &lt;- req; 43 adder &lt;- req;
40 } 44 }
41 for i := N-1; i &gt;= 0; i-- { // doesn't matter what order 45 for i := N-1; i &gt;= 0; i-- { // doesn't matter what order
42 if &lt;-reqs[i].replyc != N + 2*i { 46 if &lt;-reqs[i].replyc != N + 2*i {
43 fmt.Println(&quot;fail at&quot;, i); 47 fmt.Println(&quot;fail at&quot;, i);
44 } 48 }
45 } 49 }
46 fmt.Println(&quot;done&quot;); 50 fmt.Println(&quot;done&quot;);
47 } 51 }
</pre> </pre>
<p> <p>
One annoyance with this program is that it doesn't exit cleanly; when <code>main</code> returns One annoyance with this program is that it doesn't exit cleanly; when <code>main</code> returns
...@@ -1306,27 +1284,27 @@ there are a number of lingering goroutines blocked on communication. To solve t ...@@ -1306,27 +1284,27 @@ there are a number of lingering goroutines blocked on communication. To solve t
we can provide a second, <code>quit</code> channel to the server: we can provide a second, <code>quit</code> channel to the server:
<p> <p>
<pre> <!-- progs/server1.go /func.startServer/ /^}/ --> <pre> <!-- progs/server1.go /func.startServer/ /^}/ -->
28 func startServer(op binOp) (service chan *request, quit chan bool) { 32 func startServer(op binOp) (service chan *request, quit chan bool) {
29 service = make(chan *request); 33 service = make(chan *request);
30 quit = make(chan bool); 34 quit = make(chan bool);
31 go server(op, service, quit); 35 go server(op, service, quit);
32 return service, quit; 36 return service, quit;
33 } 37 }
</pre> </pre>
<p> <p>
It passes the quit channel to the <code>server</code> function, which uses it like this: It passes the quit channel to the <code>server</code> function, which uses it like this:
<p> <p>
<pre> <!-- progs/server1.go /func.server/ /^}/ --> <pre> <!-- progs/server1.go /func.server/ /^}/ -->
17 func server(op binOp, service chan *request, quit chan bool) { 21 func server(op binOp, service chan *request, quit chan bool) {
18 for { 22 for {
19 select { 23 select {
20 case req := &lt;-service: 24 case req := &lt;-service:
21 go run(op, req); // don't wait for it 25 go run(op, req); // don't wait for it
22 case &lt;-quit: 26 case &lt;-quit:
23 return; 27 return;
24 } 28 }
25 } 29 }
26 } 30 }
</pre> </pre>
<p> <p>
Inside <code>server</code>, a <code>select</code> statement chooses which of the multiple communications Inside <code>server</code>, a <code>select</code> statement chooses which of the multiple communications
...@@ -1340,11 +1318,11 @@ All that's left is to strobe the <code>quit</code> channel ...@@ -1340,11 +1318,11 @@ All that's left is to strobe the <code>quit</code> channel
at the end of main: at the end of main:
<p> <p>
<pre> <!-- progs/server1.go /adder,.quit/ --> <pre> <!-- progs/server1.go /adder,.quit/ -->
36 adder, quit := startServer(func(a, b int) int { return a + b }); 40 adder, quit := startServer(func(a, b int) int { return a + b });
</pre> </pre>
... ...
<pre> <!-- progs/server1.go /quit....true/ --> <pre> <!-- progs/server1.go /quit....true/ -->
51 quit &lt;- true; 55 quit &lt;- true;
</pre> </pre>
<p> <p>
There's a lot more to Go programming and concurrent programming in general but this There's a lot more to Go programming and concurrent programming in general but this
......
...@@ -26,7 +26,7 @@ Hello, World ...@@ -26,7 +26,7 @@ Hello, World
Let's start in the usual way: Let's start in the usual way:
--PROG progs/helloworld.go --PROG progs/helloworld.go /package/ END
Every Go source file declares, using a "package" statement, which package it's part of. Every Go source file declares, using a "package" statement, which package it's part of.
The "main" package's "main" function is where the program starts running (after The "main" package's "main" function is where the program starts running (after
...@@ -52,13 +52,13 @@ Echo ...@@ -52,13 +52,13 @@ Echo
Next up, here's a version of the Unix utility "echo(1)": Next up, here's a version of the Unix utility "echo(1)":
--PROG progs/echo.go --PROG progs/echo.go /package/ END
This program is small but it's doing a number of new things. In the last example, This program is small but it's doing a number of new things. In the last example,
we saw "func" introducing a function. The keywords "var", "const", and "type" we saw "func" introducing a function. The keywords "var", "const", and "type"
(not used yet) also introduce declarations, as does "import". (not used yet) also introduce declarations, as does "import".
Notice that we can group declarations of the same sort into Notice that we can group declarations of the same sort into
parenthesized, semicolon-separated lists if we want, as on lines 3-6 and 10-13. parenthesized, semicolon-separated lists if we want, as on lines 4-10 and 14-17.
But it's not necessary to do so; we could have said But it's not necessary to do so; we could have said
const Space = " " const Space = " "
...@@ -85,11 +85,11 @@ a naming conflict. ...@@ -85,11 +85,11 @@ a naming conflict.
Given "os.Stdout" we can use its "WriteString" method to print the string. Given "os.Stdout" we can use its "WriteString" method to print the string.
Having imported the "flag" package, line 8 creates a global variable to hold Having imported the "flag" package, line 12 creates a global variable to hold
the value of echo's "-n" flag. The variable "n_flag" has type "*bool", pointer the value of echo's "-n" flag. The variable "n_flag" has type "*bool", pointer
to "bool". to "bool".
In "main.main", we parse the arguments (line 16) and then create a local In "main.main", we parse the arguments (line 20) and then create a local
string variable we will use to build the output. string variable we will use to build the output.
The declaration statement has the form The declaration statement has the form
...@@ -352,7 +352,7 @@ object. We could write ...@@ -352,7 +352,7 @@ object. We could write
return n return n
but for simple structures like "File" it's easier to return the address of a nonce but for simple structures like "File" it's easier to return the address of a nonce
composite literal, as is done here on line 17. composite literal, as is done here on line 21.
We can use the factory to construct some familiar, exported variables of type "*File": We can use the factory to construct some familiar, exported variables of type "*File":
...@@ -370,9 +370,9 @@ multi-value return as a parenthesized list of declarations; syntactically ...@@ -370,9 +370,9 @@ multi-value return as a parenthesized list of declarations; syntactically
they look just like a second parameter list. The function they look just like a second parameter list. The function
"syscall.Open" "syscall.Open"
also has a multi-value return, which we can grab with the multi-variable also has a multi-value return, which we can grab with the multi-variable
declaration on line 27; it declares "r" and "e" to hold the two values, declaration on line 31; it declares "r" and "e" to hold the two values,
both of type "int64" (although you'd have to look at the "syscall" package both of type "int64" (although you'd have to look at the "syscall" package
to see that). Finally, line 28 returns two values: a pointer to the new "File" to see that). Finally, line 35 returns two values: a pointer to the new "File"
and the error. If "syscall.Open" fails, the file descriptor "r" will and the error. If "syscall.Open" fails, the file descriptor "r" will
be negative and "NewFile" will return "nil". be negative and "NewFile" will return "nil".
...@@ -406,7 +406,7 @@ set of such error values. ...@@ -406,7 +406,7 @@ set of such error values.
We can now use our new package: We can now use our new package:
--PROG progs/helloworld3.go --PROG progs/helloworld3.go /package/ END
The import of ''"./file"'' tells the compiler to use our own package rather than The import of ''"./file"'' tells the compiler to use our own package rather than
something from the directory of installed packages. something from the directory of installed packages.
...@@ -424,12 +424,12 @@ Rotting cats ...@@ -424,12 +424,12 @@ Rotting cats
Building on the "file" package, here's a simple version of the Unix utility "cat(1)", Building on the "file" package, here's a simple version of the Unix utility "cat(1)",
"progs/cat.go": "progs/cat.go":
--PROG progs/cat.go --PROG progs/cat.go /package/ END
By now this should be easy to follow, but the "switch" statement introduces some By now this should be easy to follow, but the "switch" statement introduces some
new features. Like a "for" loop, an "if" or "switch" can include an new features. Like a "for" loop, an "if" or "switch" can include an
initialization statement. The "switch" on line 14 uses one to create variables initialization statement. The "switch" on line 18 uses one to create variables
"nr" and "er" to hold the return values from "f.Read()". (The "if" on line 21 "nr" and "er" to hold the return values from "f.Read()". (The "if" on line 25
has the same idea.) The "switch" statement is general: it evaluates the cases has the same idea.) The "switch" statement is general: it evaluates the cases
from top to bottom looking for the first case that matches the value; the from top to bottom looking for the first case that matches the value; the
case expressions don't need to be constants or even integers, as long as case expressions don't need to be constants or even integers, as long as
...@@ -441,7 +441,7 @@ in a "for" statement, a missing value means "true". In fact, such a "switch" ...@@ -441,7 +441,7 @@ in a "for" statement, a missing value means "true". In fact, such a "switch"
is a form of "if-else" chain. While we're here, it should be mentioned that in is a form of "if-else" chain. While we're here, it should be mentioned that in
"switch" statements each "case" has an implicit "break". "switch" statements each "case" has an implicit "break".
Line 21 calls "Write()" by slicing the incoming buffer, which is itself a slice. Line 25 calls "Write()" by slicing the incoming buffer, which is itself a slice.
Slices provide the standard Go way to handle I/O buffers. Slices provide the standard Go way to handle I/O buffers.
Now let's make a variant of "cat" that optionally does "rot13" on its input. Now let's make a variant of "cat" that optionally does "rot13" on its input.
...@@ -466,7 +466,7 @@ we have a second implementation of the "reader" interface. ...@@ -466,7 +466,7 @@ we have a second implementation of the "reader" interface.
--PROG progs/cat_rot13.go /type.rotate13/ /end.of.rotate13/ --PROG progs/cat_rot13.go /type.rotate13/ /end.of.rotate13/
(The "rot13" function called on line 38 is trivial and not worth reproducing.) (The "rot13" function called on line 42 is trivial and not worth reproducing.)
To use the new feature, we define a flag: To use the new feature, we define a flag:
...@@ -478,7 +478,7 @@ and use it from within a mostly unchanged "cat()" function: ...@@ -478,7 +478,7 @@ and use it from within a mostly unchanged "cat()" function:
(We could also do the wrapping in "main" and leave "cat()" mostly alone, except (We could also do the wrapping in "main" and leave "cat()" mostly alone, except
for changing the type of the argument; consider that an exercise.) for changing the type of the argument; consider that an exercise.)
Lines 52 through 55 set it all up: If the "rot13" flag is true, wrap the "reader" Lines 56 through 59 set it all up: If the "rot13" flag is true, wrap the "reader"
we received into a "rotate13" and proceed. Note that the interface variables we received into a "rotate13" and proceed. Note that the interface variables
are values, not pointers: the argument is of type "reader", not "*reader", are values, not pointers: the argument is of type "reader", not "*reader",
even though under the covers it holds a pointer to a "struct". even though under the covers it holds a pointer to a "struct".
...@@ -532,7 +532,7 @@ We can apply "Sort" to any type that implements "Len", "Less", and "Swap". ...@@ -532,7 +532,7 @@ We can apply "Sort" to any type that implements "Len", "Less", and "Swap".
The "sort" package includes the necessary methods to allow sorting of The "sort" package includes the necessary methods to allow sorting of
arrays of integers, strings, etc.; here's the code for arrays of "int" arrays of integers, strings, etc.; here's the code for arrays of "int"
--PROG progs/sort.go /type.*IntArray/ /swap/ --PROG progs/sort.go /type.*IntArray/ /Swap/
Here we see methods defined for non-"struct" types. You can define methods Here we see methods defined for non-"struct" types. You can define methods
for any type you define and name in your package. for any type you define and name in your package.
...@@ -711,7 +711,7 @@ channel, and a prime number. It copies values from the input to the ...@@ -711,7 +711,7 @@ channel, and a prime number. It copies values from the input to the
output, discarding anything divisible by the prime. The unary communications output, discarding anything divisible by the prime. The unary communications
operator "&lt;-" (receive) retrieves the next value on the channel. operator "&lt;-" (receive) retrieves the next value on the channel.
--PROG progs/sieve.go /Copy/ /^}/ --PROG progs/sieve.go /Copy.the/ /^}/
The generator and filters execute concurrently. Go has The generator and filters execute concurrently. Go has
its own model of process/threads/light-weight processes/coroutines, its own model of process/threads/light-weight processes/coroutines,
...@@ -736,7 +736,7 @@ together: ...@@ -736,7 +736,7 @@ together:
--PROG progs/sieve.go /func.main/ /^}/ --PROG progs/sieve.go /func.main/ /^}/
Line 25 creates the initial channel to pass to "generate", which it Line 29 creates the initial channel to pass to "generate", which it
then starts up. As each prime pops out of the channel, a new "filter" then starts up. As each prime pops out of the channel, a new "filter"
is added to the pipeline and <i>its</i> output becomes the new value is added to the pipeline and <i>its</i> output becomes the new value
of "ch". of "ch".
...@@ -752,7 +752,7 @@ channel, launches a goroutine internally using a function literal, and ...@@ -752,7 +752,7 @@ channel, launches a goroutine internally using a function literal, and
returns the channel to the caller. It is a factory for concurrent returns the channel to the caller. It is a factory for concurrent
execution, starting the goroutine and returning its connection. execution, starting the goroutine and returning its connection.
The function literal notation (lines 8-12) allows us to construct an The function literal notation (lines 12-16) allows us to construct an
anonymous function and invoke it on the spot. Notice that the local anonymous function and invoke it on the spot. Notice that the local
variable "ch" is available to the function literal and lives on even variable "ch" is available to the function literal and lives on even
after "generate" returns. after "generate" returns.
...@@ -787,7 +787,7 @@ code that invokes the operation and responds to the request: ...@@ -787,7 +787,7 @@ code that invokes the operation and responds to the request:
--PROG progs/server.go /type.binOp/ /^}/ --PROG progs/server.go /type.binOp/ /^}/
Line 10 defines the name "binOp" to be a function taking two integers and Line 18 defines the name "binOp" to be a function taking two integers and
returning a third. returning a third.
The "server" routine loops forever, receiving requests and, to avoid blocking due to The "server" routine loops forever, receiving requests and, to avoid blocking due to
......
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
# #
# missing third arg means print one line # missing third arg means print one line
# third arg "END" means proces rest of file # third arg "END" means proces rest of file
# missing second arg means process whole file # missing second arg means process whole file
# #
# examples: # examples:
# #
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment