diff --git a/doc/go_tutorial.html b/doc/go_tutorial.html index b797de807c9..a54bcc606b7 100644 --- a/doc/go_tutorial.html +++ b/doc/go_tutorial.html @@ -32,14 +32,14 @@ cleanliness, blank lines remain blank.

Let's start in the usual way:

-

 
-01    package main
+
 
+05    package main
 

-03 import fmt "fmt" // Package implementing formatted I/O. +07 import fmt "fmt" // Package implementing formatted I/O.

-05 func main() { -06 fmt.Printf("Hello, world; or Καλημέρα κόσμε; or こんにちは 世界\n"); -07 } +09 func main() { +10 fmt.Printf("Hello, world; or Καλημέρα κόσμε; or こんにちは 世界\n"); +11 }

Every Go source file declares, using a package statement, which package it's part of. @@ -67,42 +67,42 @@ Later we'll have much more to say about printing.

Next up, here's a version of the Unix utility echo(1):

-

 
-01    package main
+
 
+05    package main
 

-03 import ( -04 "os"; -05 "flag"; -06 ) +07 import ( +08 "os"; +09 "flag"; +10 )

-08 var n_flag = flag.Bool("n", false, "don't print final newline") +12 var n_flag = flag.Bool("n", false, "don't print final newline")

-10 const ( -11 kSpace = " "; -12 kNewline = "\n"; -13 ) +14 const ( +15 kSpace = " "; +16 kNewline = "\n"; +17 )

-15 func main() { -16 flag.Parse(); // Scans the arg list and sets up flags -17 var s string = ""; -18 for i := 0; i < flag.NArg(); i++ { -19 if i > 0 { -20 s += kSpace -21 } -22 s += flag.Arg(i) -23 } -24 if !*n_flag { -25 s += kNewline -26 } -27 os.Stdout.WriteString(s); -28 } +19 func main() { +20 flag.Parse(); // Scans the arg list and sets up flags +21 var s string = ""; +22 for i := 0; i < flag.NArg(); i++ { +23 if i > 0 { +24 s += kSpace +25 } +26 s += flag.Arg(i) +27 } +28 if !*n_flag { +29 s += kNewline +30 } +31 os.Stdout.WriteString(s); +32 }

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 (not used yet) also introduce declarations, as does import. 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

@@ -131,11 +131,11 @@ a naming conflict.
 

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 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.

The declaration statement has the form @@ -169,7 +169,7 @@ the top level.) There's one in the for clause on the next line:

 
-18        for i := 0; i < flag.NArg(); i++ {
+22        for i := 0; i < flag.NArg(); i++ {
 

The flag package has parsed the arguments and left the non-flag arguments @@ -214,11 +214,11 @@ of course you can change a string variable simply by reassigning it. This snippet from strings.go is legal code:

 
-07        s := "hello";
-08        if s[1] != 'e' { os.Exit(1) }
-09        s = "good bye";
-10        var p *string = &s;
-11        *p = "ciao";
+11        s := "hello";
+12        if s[1] != 'e' { os.Exit(1) }
+13        s = "good bye";
+14        var p *string = &s;
+15        *p = "ciao";
 

However the following statements are illegal because they would modify @@ -273,19 +273,19 @@ create (efficiently) a slice reference and pass that. Using slices one can write this function (from sum.go):

 
-05    func sum(a []int) int {   // returns an int
-06        s := 0;
-07        for i := 0; i < len(a); i++ {
-08            s += a[i]
-09        }
-10        return s
-11    }
+09    func sum(a []int) int {   // returns an int
+10        s := 0;
+11        for i := 0; i < len(a); i++ {
+12            s += a[i]
+13        }
+14        return s
+15    }
 

and invoke it like this:

 
-15        s := sum(&[3]int{1,2,3});  // a slice of the array is passed to sum
+19        s := sum(&[3]int{1,2,3});  // a slice of the array is passed to sum
 

Note how the return type (int) is defined for sum() by stating it @@ -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 file.go:

 
-01    package file
+05    package file
 

-03 import ( -04 "os"; -05 "syscall"; -06 ) +07 import ( +08 "os"; +09 "syscall"; +10 )

-08 type File struct { -09 fd int; // file descriptor number -10 name string; // file name at Open time -11 } +12 type File struct { +13 fd int; // file descriptor number +14 name string; // file name at Open time +15 }

The first line declares the name of the package -- file -- @@ -442,12 +442,12 @@ will soon give it some exported, upper-case methods. First, though, here is a factory to create them:

 
-13    func newFile(fd int, name string) *File {
-14        if fd < 0 {
-15            return nil
-16        }
-17        return &File{fd, name}
-18    }
+17    func newFile(fd int, name string) *File {
+18        if fd < 0 {
+19            return nil
+20        }
+21        return &File{fd, name}
+22    }
 

This returns a pointer to a new File structure with the file descriptor and name @@ -463,29 +463,29 @@ object. We could write

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:

 
-20    var (
-21        Stdin  = newFile(0, "/dev/stdin");
-22        Stdout = newFile(1, "/dev/stdout");
-23        Stderr = newFile(2, "/dev/stderr");
-24    )
+24    var (
+25        Stdin  = newFile(0, "/dev/stdin");
+26        Stdout = newFile(1, "/dev/stdout");
+27        Stderr = newFile(2, "/dev/stderr");
+28    )
 

The newFile function was not exported because it's internal. The proper, exported factory to use is Open:

 
-26    func Open(name string, mode int, perm int) (file *File, err os.Error) {
-27        r, e := syscall.Open(name, mode, perm);
-28        if e != 0 {
-29            err = os.Errno(e);
-30        }
-31        return newFile(r, name), err
-32    }
+30    func Open(name string, mode int, perm int) (file *File, err os.Error) {
+31        r, e := syscall.Open(name, mode, perm);
+32        if e != 0 {
+33            err = os.Errno(e);
+34        }
+35        return newFile(r, name), err
+36    }
 

There are a number of new things in these few lines. First, Open returns @@ -495,9 +495,9 @@ multi-value return as a parenthesized list of declarations; syntactically they look just like a second parameter list. The function syscall.Open 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 -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 be negative and NewFile will return nil.

@@ -515,43 +515,43 @@ in parentheses before the function name. Here are some methods for *Filefile.

 
-34    func (file *File) Close() os.Error {
-35        if file == nil {
-36            return os.EINVAL
-37        }
-38        e := syscall.Close(file.fd);
-39        file.fd = -1;  // so it can't be closed again
-40        if e != 0 {
-41            return os.Errno(e);
-42        }
-43        return nil
-44    }
+38    func (file *File) Close() os.Error {
+39        if file == nil {
+40            return os.EINVAL
+41        }
+42        e := syscall.Close(file.fd);
+43        file.fd = -1;  // so it can't be closed again
+44        if e != 0 {
+45            return os.Errno(e);
+46        }
+47        return nil
+48    }
 

-46 func (file *File) Read(b []byte) (ret int, err os.Error) { -47 if file == nil { -48 return -1, os.EINVAL -49 } -50 r, e := syscall.Read(file.fd, b); -51 if e != 0 { -52 err = os.Errno(e); +50 func (file *File) Read(b []byte) (ret int, err os.Error) { +51 if file == nil { +52 return -1, os.EINVAL 53 } -54 return int(r), err -55 } +54 r, e := syscall.Read(file.fd, b); +55 if e != 0 { +56 err = os.Errno(e); +57 } +58 return int(r), err +59 }

-57 func (file *File) Write(b []byte) (ret int, err os.Error) { -58 if file == nil { -59 return -1, os.EINVAL -60 } -61 r, e := syscall.Write(file.fd, b); -62 if e != 0 { -63 err = os.Errno(e); +61 func (file *File) Write(b []byte) (ret int, err os.Error) { +62 if file == nil { +63 return -1, os.EINVAL 64 } -65 return int(r), err -66 } -

-68 func (file *File) String() string { -69 return file.name +65 r, e := syscall.Write(file.fd, b); +66 if e != 0 { +67 err = os.Errno(e); +68 } +69 return int(r), err 70 } +

+72 func (file *File) String() string { +73 return file.name +74 }

There is no implicit this and the receiver variable must be used to access @@ -569,24 +569,24 @@ set of such error values.

We can now use our new package:

-

 
-01    package main
+
 
+05    package main
 

-03 import ( -04 "./file"; -05 "fmt"; -06 "os"; -07 ) +07 import ( +08 "./file"; +09 "fmt"; +10 "os"; +11 )

-09 func main() { -10 hello := []byte{'h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '\n'}; -11 file.Stdout.Write(hello); -12 file, err := file.Open("/does/not/exist", 0, 0); -13 if file == nil { -14 fmt.Printf("can't open file; err=%s\n", err.String()); -15 os.Exit(1); -16 } -17 } +13 func main() { +14 hello := []byte{'h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '\n'}; +15 file.Stdout.Write(hello); +16 file, err := file.Open("/does/not/exist", 0, 0); +17 if file == nil { +18 fmt.Printf("can't open file; err=%s\n", err.String()); +19 os.Exit(1); +20 } +21 }

The import of ''./file'' tells the compiler to use our own package rather than @@ -606,55 +606,55 @@ Finally we can run the program: Building on the file package, here's a simple version of the Unix utility cat(1), progs/cat.go:

-

 
-01    package main
+
 
+05    package main
 

-03 import ( -04 "./file"; -05 "flag"; -06 "fmt"; -07 "os"; -08 ) +07 import ( +08 "./file"; +09 "flag"; +10 "fmt"; +11 "os"; +12 )

-10 func cat(f *file.File) { -11 const NBUF = 512; -12 var buf [NBUF]byte; -13 for { -14 switch nr, er := f.Read(&buf); true { -15 case nr < 0: -16 fmt.Fprintf(os.Stderr, "error reading from %s: %s\n", f.String(), er.String()); -17 os.Exit(1); -18 case nr == 0: // EOF -19 return; -20 case nr > 0: -21 if nw, ew := file.Stdout.Write(buf[0:nr]); nw != nr { -22 fmt.Fprintf(os.Stderr, "error writing from %s: %s\n", f.String(), ew.String()); -23 } -24 } -25 } -26 } +14 func cat(f *file.File) { +15 const NBUF = 512; +16 var buf [NBUF]byte; +17 for { +18 switch nr, er := f.Read(&buf); true { +19 case nr < 0: +20 fmt.Fprintf(os.Stderr, "error reading from %s: %s\n", f.String(), er.String()); +21 os.Exit(1); +22 case nr == 0: // EOF +23 return; +24 case nr > 0: +25 if nw, ew := file.Stdout.Write(buf[0:nr]); nw != nr { +26 fmt.Fprintf(os.Stderr, "error writing from %s: %s\n", f.String(), ew.String()); +27 } +28 } +29 } +30 }

-28 func main() { -29 flag.Parse(); // Scans the arg list and sets up flags -30 if flag.NArg() == 0 { -31 cat(file.Stdin); -32 } -33 for i := 0; i < flag.NArg(); i++ { -34 f, err := file.Open(flag.Arg(i), 0, 0); -35 if f == nil { -36 fmt.Fprintf(os.Stderr, "can't open %s: error %s\n", flag.Arg(i), err); -37 os.Exit(1); -38 } -39 cat(f); -40 f.Close(); -41 } -42 } +32 func main() { +33 flag.Parse(); // Scans the arg list and sets up flags +34 if flag.NArg() == 0 { +35 cat(file.Stdin); +36 } +37 for i := 0; i < flag.NArg(); i++ { +38 f, err := file.Open(flag.Arg(i), 0, 0); +39 if f == nil { +40 fmt.Fprintf(os.Stderr, "can't open %s: error %s\n", flag.Arg(i), err); +41 os.Exit(1); +42 } +43 cat(f); +44 f.Close(); +45 } +46 }

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 -initialization statement. The switch on line 14 uses one to create variables -nr and er to hold the return values from f.Read(). (The if on line 21 +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 25 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 case expressions don't need to be constants or even integers, as long as @@ -666,7 +666,7 @@ in a for statement, a missing value means true. In fa 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.

-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.

Now let's make a variant of cat that optionally does rot13 on its input. @@ -678,10 +678,10 @@ so let's start by defining an interface that has exactly those two methods. Here is code from progs/cat_rot13.go:

 
-22    type reader interface {
-23        Read(b []byte) (ret int, err os.Error);
-24        String() string;
-25    }
+26    type reader interface {
+27        Read(b []byte) (ret int, err os.Error);
+28        String() string;
+29    }
 

Any type that implements the two methods of reader -- regardless of whatever @@ -695,66 +695,66 @@ the type and implement the methods and with no other bookkeeping, we have a second implementation of the reader interface.

 
-27    type rotate13 struct {
-28        source    reader;
-29    }
-

-31 func newRotate13(source reader) *rotate13 { -32 return &rotate13{source} +31 type rotate13 struct { +32 source reader; 33 }

-35 func (r13 *rotate13) Read(b []byte) (ret int, err os.Error) { -36 r, e := r13.source.Read(b); -37 for i := 0; i < r; i++ { -38 b[i] = rot13(b[i]) -39 } -40 return r, e -41 } +35 func newRotate13(source reader) *rotate13 { +36 return &rotate13{source} +37 }

-43 func (r13 *rotate13) String() string { -44 return r13.source.String() +39 func (r13 *rotate13) Read(b []byte) (ret int, err os.Error) { +40 r, e := r13.source.Read(b); +41 for i := 0; i < r; i++ { +42 b[i] = rot13(b[i]) +43 } +44 return r, e 45 } -46 // end of rotate13 implementation +

+47 func (r13 *rotate13) String() string { +48 return r13.source.String() +49 } +50 // end of rotate13 implementation

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

 
-10    var rot13_flag = flag.Bool("rot13", false, "rot13 the input")
+14    var rot13_flag = flag.Bool("rot13", false, "rot13 the input")
 

and use it from within a mostly unchanged cat() function:

 
-48    func cat(r reader) {
-49        const NBUF = 512;
-50        var buf [NBUF]byte;
+52    func cat(r reader) {
+53        const NBUF = 512;
+54        var buf [NBUF]byte;
 

-52 if *rot13_flag { -53 r = newRotate13(r) -54 } -55 for { -56 switch nr, er := r.Read(&buf); { -57 case nr < 0: -58 fmt.Fprintf(os.Stderr, "error reading from %s: %s\n", r.String(), er.String()); -59 os.Exit(1); -60 case nr == 0: // EOF -61 return; -62 case nr > 0: -63 nw, ew := file.Stdout.Write(buf[0:nr]); -64 if nw != nr { -65 fmt.Fprintf(os.Stderr, "error writing from %s: %s\n", r.String(), ew.String()); -66 } -67 } -68 } -69 } +56 if *rot13_flag { +57 r = newRotate13(r) +58 } +59 for { +60 switch nr, er := r.Read(&buf); { +61 case nr < 0: +62 fmt.Fprintf(os.Stderr, "error reading from %s: %s\n", r.String(), er.String()); +63 os.Exit(1); +64 case nr == 0: // EOF +65 return; +66 case nr > 0: +67 nw, ew := file.Stdout.Write(buf[0:nr]); +68 if nw != nr { +69 fmt.Fprintf(os.Stderr, "error writing from %s: %s\n", r.String(), ew.String()); +70 } +71 } +72 } +73 }

(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.) -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 are values, not pointers: the argument is of type reader, not *reader, even though under the covers it holds a pointer to a struct. @@ -798,61 +798,35 @@ same interface variable. As an example, consider this simple sort algorithm taken from progs/sort.go:

 
-09    func Sort(data Interface) {
-10        for i := 1; i < data.Len(); i++ {
-11            for j := i; j > 0 && data.Less(j, j-1); j-- {
-12                data.Swap(j, j-1);
-13            }
-14        }
-15    }
+13    func Sort(data Interface) {
+14        for i := 1; i < data.Len(); i++ {
+15            for j := i; j > 0 && data.Less(j, j-1); j-- {
+16                data.Swap(j, j-1);
+17            }
+18        }
+19    }
 

The code needs only three methods, which we wrap into sort's Interface:

 
-03    type Interface interface {
-04        Len() int;
-05        Less(i, j int) bool;
-06        Swap(i, j int);
-07    }
+07    type Interface interface {
+08        Len() int;
+09        Less(i, j int) bool;
+10        Swap(i, j int);
+11    }
 

We can apply Sort to any type that implements Len, Less, and Swap. The sort package includes the necessary methods to allow sorting of arrays of integers, strings, etc.; here's the code for arrays of int

-

 
-29    type IntArray []int
+
 
+33    type IntArray []int
 

-31 func (p IntArray) Len() int { return len(p); } -32 func (p IntArray) Less(i, j int) bool { return p[i] < p[j]; } -33 func (p IntArray) Swap(i, j int) { p[i], p[j] = p[j], p[i]; } -

-

-36 type FloatArray []float -

-38 func (p FloatArray) Len() int { return len(p); } -39 func (p FloatArray) Less(i, j int) bool { return p[i] < p[j]; } -40 func (p FloatArray) Swap(i, j int) { p[i], p[j] = p[j], p[i]; } -

-

-43 type StringArray []string -

-45 func (p StringArray) Len() int { return len(p); } -46 func (p StringArray) Less(i, j int) bool { return p[i] < p[j]; } -47 func (p StringArray) Swap(i, j int) { p[i], p[j] = p[j], p[i]; } -

-

-50 // Convenience wrappers for common cases -

-52 func SortInts(a []int) { Sort(IntArray(a)); } -53 func SortFloats(a []float) { Sort(FloatArray(a)); } -54 func SortStrings(a []string) { Sort(StringArray(a)); } -

-

-57 func IntsAreSorted(a []int) bool { return IsSorted(IntArray(a)); } -58 func FloatsAreSorted(a []float) bool { return IsSorted(FloatArray(a)); } -59 func StringsAreSorted(a []string) bool { return IsSorted(StringArray(a)); } +35 func (p IntArray) Len() int { return len(p); } +36 func (p IntArray) Less(i, j int) bool { return p[i] < p[j]; } +37 func (p IntArray) Swap(i, j int) { p[i], p[j] = p[j], p[i]; }

Here we see methods defined for non-struct types. You can define methods @@ -863,33 +837,33 @@ uses a function in the sort package, omitted here for brevity, to test that the result is sorted.

 
-08    func ints() {
-09        data := []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586};
-10        a := sort.IntArray(data);
-11        sort.Sort(a);
-12        if !sort.IsSorted(a) {
-13            panic()
-14        }
-15    }
+12    func ints() {
+13        data := []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586};
+14        a := sort.IntArray(data);
+15        sort.Sort(a);
+16        if !sort.IsSorted(a) {
+17            panic()
+18        }
+19    }
 

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:

 
-26    type day struct {
-27        num        int;
-28        short_name string;
-29        long_name  string;
-30    }
-

-32 type dayArray struct { -33 data []*day; +30 type day struct { +31 num int; +32 short_name string; +33 long_name string; 34 }

-36 func (p *dayArray) Len() int { return len(p.data); } -37 func (p *dayArray) Less(i, j int) bool { return p.data[i].num < p.data[j].num; } -38 func (p *dayArray) Swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i]; } +36 type dayArray struct { +37 data []*day; +38 } +

+40 func (p *dayArray) Len() int { return len(p.data); } +41 func (p *dayArray) Less(i, j int) bool { return p.data[i].num < p.data[j].num; } +42 func (p *dayArray) Swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i]; }

@@ -920,8 +894,8 @@ can just say %d; Printf knows the size and signedness integer and can do the right thing for you. The snippet

 
-06        var u64 uint64 = 1<<64-1;
-07        fmt.Printf("%d %d\n", u64, int64(u64));
+06    
+07    import "fmt"
 

prints @@ -934,10 +908,10 @@ In fact, if you're lazy the format %v will print, in a simple appropriate style, any value, even an array or structure. The output of

 
-10        type T struct { a int; b string };
-11        t := T{77, "Sunset Strip"};
-12        a := []int{1, 2, 3, 4};
-13        fmt.Printf("%v %v %v\n", u64, t, a);
+10        var u64 uint64 = 1<<64-1;
+11        fmt.Printf("%d %d\n", u64, int64(u64));
+

+13 // harder stuff

is @@ -954,8 +928,8 @@ and adds a newline. The output of each of these two lines is identical to that of the Printf call above.

 
-14        fmt.Print(u64, " ", t, " ", a, "\n");
-15        fmt.Println(u64, t, a);
+14        type T struct { a int; b string };
+15        t := T{77, "Sunset Strip"};
 

If you have your own type you'd like Printf or Print to format, @@ -965,16 +939,20 @@ the method and if so, use it rather than some other formatting. Here's a simple example.

 
-05    type testType struct { a int; b string }
+05    package main
 

-07 func (t *testType) String() string { -08 return fmt.Sprint(t.a) + " " + t.b -09 } +07 import "fmt"

-11 func main() { -12 t := &testType{77, "Sunset Strip"}; -13 fmt.Println(t) -14 } +09 type testType struct { a int; b string } +

+11 func (t *testType) String() string { +12 return fmt.Sprint(t.a) + " " + t.b +13 } +

+15 func main() { +16 t := &testType{77, "Sunset Strip"}; +17 fmt.Println(t) +18 }

Since *T has a String() method, the @@ -1076,12 +1054,12 @@ coordinates the communication; as with maps and slices, use Here is the first function in progs/sieve.go:

 
-05    // Send the sequence 2, 3, 4, ... to channel 'ch'.
-06    func generate(ch chan int) {
-07        for i := 2; ; i++ {
-08            ch <- i  // Send 'i' to channel 'ch'.
-09        }
-10    }
+09    // Send the sequence 2, 3, 4, ... to channel 'ch'.
+10    func generate(ch chan int) {
+11        for i := 2; ; i++ {
+12            ch <- i  // Send 'i' to channel 'ch'.
+13        }
+14    }
 

The generate 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 output, discarding anything divisible by the prime. The unary communications operator <- (receive) retrieves the next value on the channel.

-

 
-12    // Copy the values from channel 'in' to channel 'out',
-13    // removing those divisible by 'prime'.
-14    func filter(in, out chan int, prime int) {
-15        for {
-16            i := <-in;  // Receive value of new variable 'i' from 'in'.
-17            if i % prime != 0 {
-18                out <- i  // Send 'i' to channel 'out'.
-19            }
-20        }
-21    }
+
 
+16    // Copy the values from channel 'in' to channel 'out',
+17    // removing those divisible by 'prime'.
+18    func filter(in, out chan int, prime int) {
+19        for {
+20            i := <-in;  // Receive value of new variable 'i' from 'in'.
+21            if i % prime != 0 {
+22                out <- i  // Send 'i' to channel 'out'.
+23            }
+24        }
+25    }
 

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

 
-24    func main() {
-25        ch := make(chan int);  // Create a new channel.
-26        go generate(ch);  // Start generate() as a goroutine.
-27        for {
-28            prime := <-ch;
-29            fmt.Println(prime);
-30            ch1 := make(chan int);
-31            go filter(ch, ch1, prime);
-32            ch = ch1
-33        }
-34    }
+28    func main() {
+29        ch := make(chan int);  // Create a new channel.
+30        go generate(ch);  // Start generate() as a goroutine.
+31        for {
+32            prime := <-ch;
+33            fmt.Println(prime);
+34            ch1 := make(chan int);
+35            go filter(ch, ch1, prime);
+36            ch = ch1
+37        }
+38    }
 

-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 is added to the pipeline and its output becomes the new value of ch. @@ -1156,15 +1134,15 @@ in this style of programming. Here is a variant version of generate, from progs/sieve1.go:

 
-06    func generate() chan int {
-07        ch := make(chan int);
-08        go func(){
-09            for i := 2; ; i++ {
-10                ch <- i
-11            }
-12        }();
-13        return ch;
-14    }
+10    func generate() chan int {
+11        ch := make(chan int);
+12        go func(){
+13            for i := 2; ; i++ {
+14                ch <- i
+15            }
+16        }();
+17        return ch;
+18    }
 

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 returns the channel to the caller. It is a factory for concurrent 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 variable ch is available to the function literal and lives on even after generate returns. @@ -1180,46 +1158,46 @@ after generate returns. The same change can be made to filter:

 
-17    func filter(in chan int, prime int) chan int {
-18        out := make(chan int);
-19        go func() {
-20            for {
-21                if i := <-in; i % prime != 0 {
-22                    out <- i
-23                }
-24            }
-25        }();
-26        return out;
-27    }
+21    func filter(in chan int, prime int) chan int {
+22        out := make(chan int);
+23        go func() {
+24            for {
+25                if i := <-in; i % prime != 0 {
+26                    out <- i
+27                }
+28            }
+29        }();
+30        return out;
+31    }
 

The sieve 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:

 
-29    func sieve() chan int {
-30        out := make(chan int);
-31        go func() {
-32            ch := generate();
-33            for {
-34                prime := <-ch;
-35                out <- prime;
-36                ch = filter(ch, prime);
-37            }
-38        }();
-39        return out;
-40    }
+33    func sieve() chan int {
+34        out := make(chan int);
+35        go func() {
+36            ch := generate();
+37            for {
+38                prime := <-ch;
+39                out <- prime;
+40                ch = filter(ch, prime);
+41            }
+42        }();
+43        return out;
+44    }
 

Now main's interface to the prime sieve is a channel of primes:

 
-42    func main() {
-43        primes := sieve();
-44        for {
-45            fmt.Println(<-primes);
-46        }
-47    }
+46    func main() {
+47        primes := sieve();
+48        for {
+49            fmt.Println(<-primes);
+50        }
+51    }
 

Multiplexing

@@ -1232,48 +1210,48 @@ to illustrate the idea. It starts by defining a request type, whic that will be used for the reply.

 
-05    type request struct {
-06        a, b    int;
-07        replyc  chan int;
-08    }
+09    type request struct {
+10        a, b    int;
+11        replyc  chan int;
+12    }
 

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:

 
-10    type binOp func(a, b int) int
+14    type binOp func(a, b int) int
 

-12 func run(op binOp, req *request) { -13 reply := op(req.a, req.b); -14 req.replyc <- reply; -15 } +16 func run(op binOp, req *request) { +17 reply := op(req.a, req.b); +18 req.replyc <- reply; +19 }

-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.

The server routine loops forever, receiving requests and, to avoid blocking due to a long-running operation, starting a goroutine to do the actual work.

 
-17    func server(op binOp, service chan *request) {
-18        for {
-19            req := <-service;
-20            go run(op, req);  // don't wait for it
-21        }
-22    }
+21    func server(op binOp, service chan *request) {
+22        for {
+23            req := <-service;
+24            go run(op, req);  // don't wait for it
+25        }
+26    }
 

We construct a server in a familiar way, starting it up and returning a channel to connect to it:

 
-24    func startServer(op binOp) chan *request {
-25        req := make(chan *request);
-26        go server(op, req);
-27        return req;
-28    }
+28    func startServer(op binOp) chan *request {
+29        req := make(chan *request);
+30        go server(op, req);
+31        return req;
+32    }
 

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 does it check the results.

 
-30    func main() {
-31        adder := startServer(func(a, b int) int { return a + b });
-32        const N = 100;
-33        var reqs [N]request;
-34        for i := 0; i < N; i++ {
-35            req := &reqs[i];
-36            req.a = i;
-37            req.b = i + N;
-38            req.replyc = make(chan int);
-39            adder <- req;
-40        }
-41        for i := N-1; i >= 0; i-- {   // doesn't matter what order
-42            if <-reqs[i].replyc != N + 2*i {
-43                fmt.Println("fail at", i);
-44            }
-45        }
-46        fmt.Println("done");
-47    }
+34    func main() {
+35        adder := startServer(func(a, b int) int { return a + b });
+36        const N = 100;
+37        var reqs [N]request;
+38        for i := 0; i < N; i++ {
+39            req := &reqs[i];
+40            req.a = i;
+41            req.b = i + N;
+42            req.replyc = make(chan int);
+43            adder <- req;
+44        }
+45        for i := N-1; i >= 0; i-- {   // doesn't matter what order
+46            if <-reqs[i].replyc != N + 2*i {
+47                fmt.Println("fail at", i);
+48            }
+49        }
+50        fmt.Println("done");
+51    }
 

One annoyance with this program is that it doesn't exit cleanly; when main returns @@ -1306,27 +1284,27 @@ there are a number of lingering goroutines blocked on communication. To solve t we can provide a second, quit channel to the server:

 
-28    func startServer(op binOp) (service chan *request, quit chan bool) {
-29        service = make(chan *request);
-30        quit = make(chan bool);
-31        go server(op, service, quit);
-32        return service, quit;
-33    }
+32    func startServer(op binOp) (service chan *request, quit chan bool) {
+33        service = make(chan *request);
+34        quit = make(chan bool);
+35        go server(op, service, quit);
+36        return service, quit;
+37    }
 

It passes the quit channel to the server function, which uses it like this:

 
-17    func server(op binOp, service chan *request, quit chan bool) {
-18        for {
-19            select {
-20            case req := <-service:
-21                go run(op, req);  // don't wait for it
-22            case <-quit:
-23                return;
-24            }
-25        }
-26    }
+21    func server(op binOp, service chan *request, quit chan bool) {
+22        for {
+23            select {
+24            case req := <-service:
+25                go run(op, req);  // don't wait for it
+26            case <-quit:
+27                return;
+28            }
+29        }
+30    }
 

Inside server, a select statement chooses which of the multiple communications @@ -1340,11 +1318,11 @@ All that's left is to strobe the quit channel at the end of main:

 
-36        adder, quit := startServer(func(a, b int) int { return a + b });
+40        adder, quit := startServer(func(a, b int) int { return a + b });
 
...
 
-51        quit <- true;
+55        quit <- true;
 

There's a lot more to Go programming and concurrent programming in general but this diff --git a/doc/go_tutorial.txt b/doc/go_tutorial.txt index c1e47045a78..3d808da93f2 100644 --- a/doc/go_tutorial.txt +++ b/doc/go_tutorial.txt @@ -26,7 +26,7 @@ Hello, World 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. The "main" package's "main" function is where the program starts running (after @@ -52,13 +52,13 @@ Echo 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, we saw "func" introducing a function. The keywords "var", "const", and "type" (not used yet) also introduce declarations, as does "import". 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 const Space = " " @@ -85,11 +85,11 @@ a naming conflict. 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 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. The declaration statement has the form @@ -352,7 +352,7 @@ object. We could write return n 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": @@ -370,9 +370,9 @@ multi-value return as a parenthesized list of declarations; syntactically they look just like a second parameter list. The function "syscall.Open" 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 -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 be negative and "NewFile" will return "nil". @@ -406,7 +406,7 @@ set of such error values. 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 something from the directory of installed packages. @@ -424,12 +424,12 @@ Rotting cats Building on the "file" package, here's a simple version of the Unix utility "cat(1)", "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 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 -"nr" and "er" to hold the return values from "f.Read()". (The "if" on line 21 +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 25 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 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" 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". -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. 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. --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: @@ -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 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 are values, not pointers: the argument is of type "reader", not "*reader", 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". The "sort" package includes the necessary methods to allow sorting of 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 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 output, discarding anything divisible by the prime. The unary communications operator "<-" (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 its own model of process/threads/light-weight processes/coroutines, @@ -736,7 +736,7 @@ together: --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" is added to the pipeline and its output becomes the new value of "ch". @@ -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 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 variable "ch" is available to the function literal and lives on even after "generate" returns. @@ -787,7 +787,7 @@ code that invokes the operation and responds to the request: --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. The "server" routine loops forever, receiving requests and, to avoid blocking due to diff --git a/doc/prog.sh b/doc/prog.sh index 26a5908466e..6a540980aad 100755 --- a/doc/prog.sh +++ b/doc/prog.sh @@ -10,7 +10,7 @@ # # missing third arg means print one line # third arg "END" means proces rest of file -# missing second arg means process whole file +# missing second arg means process whole file # # examples: #