2008-09-12 17:03:16 -06:00
|
|
|
Let's Go
|
2008-09-10 12:46:05 -06:00
|
|
|
----
|
|
|
|
|
|
|
|
Rob Pike
|
|
|
|
|
|
|
|
----
|
2009-03-18 15:09:16 -06:00
|
|
|
(March 18, 2009)
|
2008-09-10 12:46:05 -06:00
|
|
|
|
|
|
|
|
|
|
|
This document is a tutorial introduction to the basics of the Go systems programming
|
2008-09-10 18:11:04 -06:00
|
|
|
language, intended for programmers familiar with C or C++. It is not a comprehensive
|
2008-09-12 17:03:16 -06:00
|
|
|
guide to the language; at the moment the document closest to that is the draft
|
|
|
|
specification:
|
2008-09-10 18:11:04 -06:00
|
|
|
|
2008-09-22 12:29:40 -06:00
|
|
|
/doc/go_spec.html
|
2008-09-10 18:11:04 -06:00
|
|
|
|
|
|
|
To check out the compiler and tools and be ready to run Go programs, see
|
|
|
|
|
|
|
|
/doc/go_setup.html
|
|
|
|
|
|
|
|
The presentation proceeds through a series of modest programs to illustrate
|
|
|
|
key features of the language. All the programs work (at time of writing) and are
|
|
|
|
checked in at
|
|
|
|
|
|
|
|
/doc/progs
|
|
|
|
|
|
|
|
Program snippets are annotated with the line number in the original file; for
|
|
|
|
cleanliness, blank lines remain blank.
|
|
|
|
|
|
|
|
Hello, World
|
|
|
|
----
|
|
|
|
|
|
|
|
Let's start in the usual way:
|
2008-09-10 12:46:05 -06:00
|
|
|
|
|
|
|
--PROG progs/helloworld.go
|
|
|
|
|
2009-02-04 16:13:07 -07:00
|
|
|
Every Go source file declares, using a "package" statement, which package it's part of.
|
2008-09-10 18:11:04 -06:00
|
|
|
The "main" package's "main" function is where the program starts running (after
|
2009-03-18 15:09:16 -06:00
|
|
|
any initialization). It may also import other packages to use their facilities.
|
|
|
|
This program imports the package "fmt" to gain access to
|
|
|
|
our old, now capitalized and package-qualified friend, "fmt.Printf".
|
2008-09-10 18:11:04 -06:00
|
|
|
|
|
|
|
Function declarations are introduced with the "func" keyword.
|
|
|
|
|
|
|
|
Notice that string constants can contain Unicode characters, encoded in UTF-8.
|
|
|
|
Go is defined to accept UTF-8 input. Strings are arrays of bytes, usually used
|
|
|
|
to store Unicode strings represented in UTF-8.
|
|
|
|
|
|
|
|
The comment convention is the same as in C++:
|
|
|
|
|
|
|
|
/* ... */
|
|
|
|
// ...
|
|
|
|
|
2009-01-09 16:16:31 -07:00
|
|
|
Later we'll have much more to say about printing.
|
|
|
|
|
2008-09-10 18:11:04 -06:00
|
|
|
Echo
|
|
|
|
----
|
|
|
|
|
|
|
|
Next up, here's a version of the Unix utility "echo(1)":
|
|
|
|
|
|
|
|
--PROG progs/echo.go
|
|
|
|
|
2009-01-09 16:16:31 -07:00
|
|
|
This program is small but it's doing a number of new things. In the last example,
|
2008-09-10 18:11:04 -06:00
|
|
|
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.
|
|
|
|
But it's not necessary to do so; we could have said
|
|
|
|
|
|
|
|
const Space = " "
|
|
|
|
const Newline = "\n"
|
|
|
|
|
|
|
|
Semicolons aren't needed here; in fact, semicolons are unnecessary after any
|
|
|
|
top-level declaration, even though they are needed as separators <i>within</i>
|
|
|
|
a parenthesized list of declarations.
|
|
|
|
|
2009-03-18 15:09:16 -06:00
|
|
|
This program imports the ""os"" package to access its "Stdout" variable, of type
|
|
|
|
"*os.File". The "import" statement is actually a declaration: in its general form,
|
|
|
|
as used in our ``hello world'' program,
|
|
|
|
it names the identifier ("fmt")
|
|
|
|
that will be used to access members of the package imported from the file (""fmt""),
|
|
|
|
found in the current directory or in a standard location.
|
|
|
|
In this program, though, we've dropped the explicit name from the imports; by default,
|
2009-01-09 16:16:31 -07:00
|
|
|
packages are imported using the name defined by the imported package,
|
2009-03-18 15:09:16 -06:00
|
|
|
which by convention is of course the file name itself. Our ``hello world'' program
|
|
|
|
could have said just "import "fmt"".
|
|
|
|
|
|
|
|
You can specify your
|
2009-01-09 16:16:31 -07:00
|
|
|
own import names if you want but it's only necessary if you need to resolve
|
|
|
|
a naming conflict.
|
|
|
|
|
2009-03-18 15:09:16 -06:00
|
|
|
Given "os.Stdout" we can use its "WriteString" method to print the string.
|
|
|
|
|
2009-01-09 16:16:31 -07:00
|
|
|
Having imported the "flag" package, line 8 creates a global variable to hold
|
|
|
|
the value of echo's "-n" flag. The variable "n_flag" has type "*bool", pointer
|
|
|
|
to "bool".
|
2008-09-10 18:11:04 -06:00
|
|
|
|
|
|
|
In "main.main", we parse the arguments (line 16) and then create a local
|
|
|
|
string variable we will use to build the output.
|
|
|
|
|
|
|
|
The declaration statement has the form
|
|
|
|
|
|
|
|
var s string = "";
|
|
|
|
|
|
|
|
This is the "var" keyword, followed by the name of the variable, followed by
|
|
|
|
its type, followed by an equals sign and an initial value for the variable.
|
|
|
|
|
|
|
|
Go tries to be terse, and this declaration could be shortened. Since the
|
|
|
|
string constant is of type string, we don't have to tell the compiler that.
|
|
|
|
We could write
|
|
|
|
|
|
|
|
var s = "";
|
|
|
|
|
|
|
|
or we could go even shorter and write the idiom
|
|
|
|
|
|
|
|
s := "";
|
|
|
|
|
2009-01-09 16:16:31 -07:00
|
|
|
The ":=" operator is used a lot in Go to represent an initializing declaration.
|
|
|
|
(For those who know Limbo, its ":=" construct is the same, but notice
|
|
|
|
that Go has no colon after the name in a full "var" declaration.
|
|
|
|
Also, for simplicity of parsing, ":=" only works inside functions, not at
|
|
|
|
the top level.)
|
|
|
|
There's one in the "for" clause on the next line:
|
2008-09-10 18:11:04 -06:00
|
|
|
|
|
|
|
--PROG progs/echo.go /for/
|
|
|
|
|
2009-01-09 16:16:31 -07:00
|
|
|
The "flag" package has parsed the arguments and left the non-flag arguments
|
2008-09-11 11:21:02 -06:00
|
|
|
in a list that can be iterated over in the obvious way.
|
2008-09-10 18:11:04 -06:00
|
|
|
|
|
|
|
The Go "for" statement differs from that of C in a number of ways. First,
|
|
|
|
it's the only looping construct; there is no "while" or "do". Second,
|
|
|
|
there are no parentheses on the clause, but the braces on the body
|
2009-01-09 16:16:31 -07:00
|
|
|
are mandatory. The same applies to the "if" and "switch" statements.
|
|
|
|
Later examples will show some other ways "for" can be written.
|
2008-09-10 18:11:04 -06:00
|
|
|
|
2009-01-09 16:16:31 -07:00
|
|
|
The body of the loop builds up the string "s" by appending (using "+=")
|
2008-09-10 18:11:04 -06:00
|
|
|
the flags and separating spaces. After the loop, if the "-n" flag is not
|
|
|
|
set, it appends a newline, and then writes the result.
|
|
|
|
|
|
|
|
Notice that "main.main" is a niladic function with no return type.
|
|
|
|
It's defined that way. Falling off the end of "main.main" means
|
|
|
|
''success''; if you want to signal erroneous return, use
|
2008-09-10 12:46:05 -06:00
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
sys.Exit(1)
|
2008-09-10 12:46:05 -06:00
|
|
|
|
2008-09-10 18:11:04 -06:00
|
|
|
The "sys" package is built in and contains some essentials for getting
|
2009-01-20 20:32:36 -07:00
|
|
|
started; for instance, "sys.Args" is an array used by the
|
|
|
|
"flag" package to access the command-line arguments.
|
2008-09-10 12:46:05 -06:00
|
|
|
|
2008-09-11 11:21:02 -06:00
|
|
|
An Interlude about Types
|
|
|
|
----
|
|
|
|
|
|
|
|
Go has some familiar types such as "int" and "float", which represent
|
|
|
|
values of the ''appropriate'' size for the machine. It also defines
|
|
|
|
specifically-sized types such as "int8", "float64", and so on, plus
|
2009-01-09 16:16:31 -07:00
|
|
|
unsigned integer types such as "uint", "uint32", etc. These are
|
|
|
|
distinct types; even if "int" and "int32" are both 32 bits in size,
|
|
|
|
they are not the same type. There is also a "byte" synonym for
|
|
|
|
"uint8", which is the element type for strings.
|
2008-09-11 11:21:02 -06:00
|
|
|
|
|
|
|
Speaking of "string", that's a built-in type as well. Strings are
|
|
|
|
<i>immutable values</i> -- they are not just arrays of "byte" values.
|
|
|
|
Once you've built a string <i>value</i>, you can't change it, although
|
|
|
|
of course you can change a string <i>variable</i> simply by
|
|
|
|
reassigning it. This snippet from "strings.go" is legal code:
|
|
|
|
|
|
|
|
--PROG progs/strings.go /hello/ /ciao/
|
|
|
|
|
|
|
|
However the following statements are illegal because they would modify
|
|
|
|
a "string" value:
|
|
|
|
|
|
|
|
s[0] = 'x';
|
|
|
|
(*p)[1] = 'y';
|
|
|
|
|
|
|
|
In C++ terms, Go strings are a bit like "const strings", while pointers
|
|
|
|
to strings are analogous to "const string" references.
|
|
|
|
|
|
|
|
Yes, there are pointers. However, Go simplifies their use a little;
|
|
|
|
read on.
|
|
|
|
|
|
|
|
Arrays are declared like this:
|
|
|
|
|
|
|
|
var array_of_int [10]int;
|
|
|
|
|
|
|
|
Arrays, like strings, are values, but they are mutable. This differs
|
|
|
|
from C, in which "array_of_int" would be usable as a pointer to "int".
|
|
|
|
In Go, since arrays are values, it's meaningful (and useful) to talk
|
|
|
|
about pointers to arrays.
|
|
|
|
|
|
|
|
The size of the array is part of its type; however, one can declare
|
2009-01-09 16:16:31 -07:00
|
|
|
a <i>slice</i> variable, to which one can assign any array value
|
|
|
|
with the same element type. Slices look a lot like arrays but have
|
|
|
|
no explicit size ("[]" vs. "[10]") and they reference a segment of
|
|
|
|
an underlying, often anonymous, regular array. Multiple slices
|
|
|
|
can share data if they represent pieces of the same array;
|
|
|
|
multiple arrays can never share data.
|
|
|
|
|
|
|
|
Slices are actually much more common in Go programs than
|
|
|
|
regular arrays; they're more flexible, have reference semantics,
|
|
|
|
and are efficient. What they lack is the precise control of storage
|
|
|
|
layout of a regular array; if you want to have a hundred elements
|
|
|
|
of an array stored within your structure, you should use a regular
|
|
|
|
array.
|
|
|
|
|
|
|
|
When passing an array to a function, you almost always want
|
|
|
|
to declare the formal parameter to be a slice. Go will automatically
|
|
|
|
create (efficiently) a slice reference and pass that.
|
|
|
|
|
|
|
|
Using slices one can write this function (from "sum.go"):
|
2008-09-11 11:21:02 -06:00
|
|
|
|
|
|
|
--PROG progs/sum.go /sum/ /^}/
|
|
|
|
|
|
|
|
and invoke it like this:
|
|
|
|
|
|
|
|
--PROG progs/sum.go /1,2,3/
|
|
|
|
|
|
|
|
Note how the return type ("int") is defined for "sum()" by stating it
|
2009-01-09 16:16:31 -07:00
|
|
|
after the parameter list.
|
|
|
|
The expression "[3]int{1,2,3}" -- a type followed by a brace-bounded expression
|
|
|
|
-- is a constructor for a value, in this case an array of 3 "ints". We pass it
|
|
|
|
to "sum()" by (automatically) promoting it to a slice.
|
|
|
|
|
|
|
|
If you are creating a regular array but want the compiler to count the
|
|
|
|
elements for you, use "..." as the array size:
|
|
|
|
|
|
|
|
s := sum([...]int{1,2,3});
|
2008-09-11 11:21:02 -06:00
|
|
|
|
2009-01-09 16:16:31 -07:00
|
|
|
In practice, though, unless you're meticulous about storage layout within a
|
|
|
|
data structure, a slice - using empty brackets - is all you need:
|
|
|
|
|
|
|
|
s := sum([]int{1,2,3});
|
|
|
|
|
|
|
|
There are also maps, which you can initialize like this:
|
2008-09-11 11:21:02 -06:00
|
|
|
|
|
|
|
m := map[string] int {"one":1 , "two":2}
|
|
|
|
|
2009-01-09 16:16:31 -07:00
|
|
|
The built-in function "len()", which returns number of elements,
|
|
|
|
makes its first appearance in "sum". It works on strings, arrays,
|
|
|
|
slices, and maps.
|
|
|
|
|
|
|
|
|
|
|
|
An Interlude about Allocation
|
|
|
|
----
|
|
|
|
|
|
|
|
Most types in Go are values. If you have an "int" or a "struct"
|
|
|
|
or an array, assignment
|
|
|
|
copies the contents of the object. To allocate something on the stack,
|
|
|
|
just declare a variable. To allocate it on the heap, use "new()", which
|
|
|
|
returns a pointer to the allocated storage.
|
|
|
|
|
|
|
|
type T struct { a, b int }
|
|
|
|
var t *T = new(T);
|
|
|
|
|
|
|
|
or the more idiomatic
|
|
|
|
|
|
|
|
t := new(T);
|
|
|
|
|
|
|
|
Some types - maps, slices, and channels (see below) have reference semantics.
|
|
|
|
If you're holding a slice or a map and you modify its contents, other variables
|
2009-02-04 16:13:07 -07:00
|
|
|
referencing the same underlying data will see the modification. For these three
|
|
|
|
types you want to use the built-in function "make()":
|
2009-01-09 16:16:31 -07:00
|
|
|
|
|
|
|
m := make(map[string] int);
|
2008-09-11 11:21:02 -06:00
|
|
|
|
2009-02-04 16:13:07 -07:00
|
|
|
This statement initializes a new map ready to store entries.
|
|
|
|
If you just declare the map, as in
|
2008-09-11 11:21:02 -06:00
|
|
|
|
2009-01-09 16:16:31 -07:00
|
|
|
var m map[string] int;
|
2008-09-11 11:21:02 -06:00
|
|
|
|
2009-02-04 16:13:07 -07:00
|
|
|
it creates a "nil" reference that cannot hold anything. To use the map,
|
2009-01-09 16:16:31 -07:00
|
|
|
you must first initialize the reference using "make()" or by assignment to an
|
|
|
|
existing map.
|
|
|
|
|
2009-02-04 16:13:07 -07:00
|
|
|
Note that "new(T)" returns type "*T" while "make(T)" returns type
|
|
|
|
"T". If you (mistakenly) allocate a reference object with "new()",
|
|
|
|
you receive a pointer to an uninitialized reference, equivalent to
|
|
|
|
declaring an uninitialized variable and taking its address.
|
2008-09-11 11:21:02 -06:00
|
|
|
|
|
|
|
An Interlude about Constants
|
|
|
|
----
|
|
|
|
|
|
|
|
Although integers come in lots of sizes in Go, integer constants do not.
|
|
|
|
There are no constants like "0ll" or "0x0UL". Instead, integer
|
2008-09-16 12:00:11 -06:00
|
|
|
constants are evaluated as ideal, large-precision values that
|
|
|
|
can overflow only when they are assigned to an integer variable with
|
|
|
|
too little precision to represent the value.
|
2008-09-11 11:21:02 -06:00
|
|
|
|
|
|
|
const hard_eight = (1 << 100) >> 97 // legal
|
|
|
|
|
|
|
|
There are nuances that deserve redirection to the legalese of the
|
|
|
|
language specification but here are some illustrative examples:
|
|
|
|
|
|
|
|
var a uint64 = 0 // a has type uint64, value 0
|
2009-01-09 16:16:31 -07:00
|
|
|
a := uint64(0) // equivalent; use a "conversion"
|
2008-09-11 11:21:02 -06:00
|
|
|
i := 0x1234 // i gets default type: int
|
|
|
|
var j int = 1e6 // legal - 1000000 is representable in an int
|
|
|
|
x := 1.5 // a float
|
2009-01-09 16:16:31 -07:00
|
|
|
i3div2 := 3/2 // integer division - result is 1
|
|
|
|
f3div2 := 3./2. // floating point division - result is 1.5
|
2008-09-11 11:21:02 -06:00
|
|
|
|
2009-01-09 16:16:31 -07:00
|
|
|
Conversions only work for simple cases such as converting "ints" of one
|
|
|
|
sign or size to another, and between "ints" and "floats", plus a few other
|
|
|
|
simple cases. There are no automatic numeric conversions of any kind in Go,
|
2008-09-11 11:21:02 -06:00
|
|
|
other than that of making constants have concrete size and type when
|
|
|
|
assigned to a variable.
|
2008-09-12 17:03:16 -06:00
|
|
|
|
|
|
|
An I/O Package
|
|
|
|
----
|
|
|
|
|
|
|
|
Next we'll look at a simple package for doing file I/O with the usual
|
2009-03-16 23:53:23 -06:00
|
|
|
sort of open/close/read/write interface. Here's the start of "file.go":
|
2008-09-12 17:03:16 -06:00
|
|
|
|
2009-03-16 23:53:23 -06:00
|
|
|
--PROG progs/file.go /package/ /^}/
|
2008-09-12 17:03:16 -06:00
|
|
|
|
2009-03-16 23:53:23 -06:00
|
|
|
The first line declares the name of the package -- "file" --
|
2009-01-09 16:16:31 -07:00
|
|
|
and then we import two packages. The "os" package hides the differences
|
|
|
|
between various operating systems to give a consistent view of files and
|
|
|
|
so on; here we're only going to use its error handling utilities
|
|
|
|
and reproduce the rudiments of its file I/O.
|
|
|
|
|
|
|
|
The other item is the low-level, external "syscall" package, which provides
|
2008-09-12 17:03:16 -06:00
|
|
|
a primitive interface to the underlying operating system's calls.
|
|
|
|
|
|
|
|
Next is a type definition: the "type" keyword introduces a type declaration,
|
2009-03-16 23:53:23 -06:00
|
|
|
in this case a data structure called "File".
|
|
|
|
To make things a little more interesting, our "File" includes the name of the file
|
2009-01-20 20:32:36 -07:00
|
|
|
that the file descriptor refers to.
|
2008-09-12 17:03:16 -06:00
|
|
|
|
2009-03-16 23:53:23 -06:00
|
|
|
Because "File" starts with a capital letter, the type is available outside the package,
|
2009-01-20 20:32:36 -07:00
|
|
|
that is, by users of the package. In Go the rule about visibility of information is
|
|
|
|
simple: if a name (of a top-level type, function, method, constant, variable, or of
|
|
|
|
a structure field) is capitalized, users of the package may see it. Otherwise, the
|
|
|
|
name and hence the thing being named is visible only inside the package in which
|
2009-02-04 16:13:07 -07:00
|
|
|
it is declared. This is more than a convention; the rule is enforced by the compiler.
|
|
|
|
In Go, the term for publicly visible names is ''exported''.
|
2008-09-12 17:03:16 -06:00
|
|
|
|
2009-03-16 23:53:23 -06:00
|
|
|
In the case of "File", all its fields are lower case and so invisible to users, but we
|
2009-01-20 20:32:36 -07:00
|
|
|
will soon give it some exported, upper-case methods.
|
|
|
|
|
|
|
|
First, though, here is a factory to create them:
|
|
|
|
|
2009-03-16 23:53:23 -06:00
|
|
|
--PROG progs/file.go /newFile/ /^}/
|
2008-09-12 17:03:16 -06:00
|
|
|
|
2009-03-16 23:53:23 -06:00
|
|
|
This returns a pointer to a new "File" structure with the file descriptor and name
|
2009-01-09 16:16:31 -07:00
|
|
|
filled in. This code uses Go's notion of a ''composite literal'', analogous to
|
2009-02-04 16:13:07 -07:00
|
|
|
the ones used to build maps and arrays, to construct a new heap-allocated
|
|
|
|
object. We could write
|
2009-01-09 16:16:31 -07:00
|
|
|
|
2009-03-16 23:53:23 -06:00
|
|
|
n := new(File);
|
|
|
|
n.fd = fd;
|
2009-01-09 16:16:31 -07:00
|
|
|
n.name = name;
|
|
|
|
return n
|
|
|
|
|
2009-03-16 23:53:23 -06:00
|
|
|
but for simple structures like "File" it's easier to return the address of a nonce
|
2009-01-09 16:16:31 -07:00
|
|
|
composite literal, as is done here on line 17.
|
|
|
|
|
2009-03-16 23:53:23 -06:00
|
|
|
We can use the factory to construct some familiar, exported variables of type "*File":
|
2008-09-12 17:03:16 -06:00
|
|
|
|
2009-03-16 23:53:23 -06:00
|
|
|
--PROG progs/file.go /var/ /^.$/
|
2008-09-12 17:03:16 -06:00
|
|
|
|
2009-03-16 23:53:23 -06:00
|
|
|
The "newFile" function was not exported because it's internal. The proper,
|
2009-01-20 20:32:36 -07:00
|
|
|
exported factory to use is "Open":
|
2008-09-12 17:03:16 -06:00
|
|
|
|
2009-03-16 23:53:23 -06:00
|
|
|
--PROG progs/file.go /func.Open/ /^}/
|
2008-09-12 17:03:16 -06:00
|
|
|
|
|
|
|
There are a number of new things in these few lines. First, "Open" returns
|
2009-03-16 23:53:23 -06:00
|
|
|
multiple values, an "File" and an error (more about errors in a moment).
|
2009-01-09 16:16:31 -07:00
|
|
|
We declare the
|
|
|
|
multi-value return as a parenthesized list of declarations; syntactically
|
|
|
|
they look just like a second parameter list. The function
|
2009-01-20 20:32:36 -07:00
|
|
|
"syscall.Open"
|
2008-09-12 17:03:16 -06:00
|
|
|
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,
|
|
|
|
both of type "int64" (although you'd have to look at the "syscall" package
|
2009-03-16 23:53:23 -06:00
|
|
|
to see that). Finally, line 28 returns two values: a pointer to the new "File"
|
2009-01-20 20:32:36 -07:00
|
|
|
and the error. If "syscall.Open" fails, the file descriptor "r" will
|
2009-03-16 23:53:23 -06:00
|
|
|
be negative and "NewFile" will return "nil".
|
2008-09-12 17:03:16 -06:00
|
|
|
|
2009-01-09 16:16:31 -07:00
|
|
|
About those errors: The "os" library includes a general notion of an error
|
|
|
|
string, maintaining a unique set of errors throughout the program. It's a
|
|
|
|
good idea to use its facility in your own interfaces, as we do here, for
|
|
|
|
consistent error handling throughout Go code. In "Open" we use the
|
|
|
|
routine "os.ErrnoToError" to translate Unix's integer "errno" value into
|
|
|
|
an error string, which will be stored in a unique instance of "*os.Error".
|
|
|
|
|
2009-03-16 23:53:23 -06:00
|
|
|
Now that we can build "Files", we can write methods for them. To declare
|
2008-09-12 17:03:16 -06:00
|
|
|
a method of a type, we define a function to have an explicit receiver
|
|
|
|
of that type, placed
|
2009-03-16 23:53:23 -06:00
|
|
|
in parentheses before the function name. Here are some methods for "*File",
|
|
|
|
each of which declares a receiver variable "file".
|
2008-09-12 17:03:16 -06:00
|
|
|
|
2009-03-16 23:53:23 -06:00
|
|
|
--PROG progs/file.go /Close/ END
|
2008-09-12 17:03:16 -06:00
|
|
|
|
|
|
|
There is no implicit "this" and the receiver variable must be used to access
|
|
|
|
members of the structure. Methods are not declared within
|
|
|
|
the "struct" declaration itself. The "struct" declaration defines only data members.
|
2009-01-09 16:16:31 -07:00
|
|
|
In fact, methods can be created for any type you name, such as an integer or
|
2009-02-04 16:13:07 -07:00
|
|
|
array, not just for "structs". We'll see an example with arrays later.
|
2009-01-09 16:16:31 -07:00
|
|
|
|
2009-02-04 16:13:07 -07:00
|
|
|
The "String" method is so called because of printing convention we'll
|
|
|
|
describe later.
|
|
|
|
|
|
|
|
The methods use the public variable "os.EINVAL" to return the ("*os.Error"
|
2009-01-09 16:16:31 -07:00
|
|
|
version of the) Unix error code EINVAL. The "os" library defines a standard
|
|
|
|
set of such error values.
|
2008-09-12 17:03:16 -06:00
|
|
|
|
|
|
|
Finally, we can use our new package:
|
|
|
|
|
|
|
|
--PROG progs/helloworld3.go
|
|
|
|
|
2009-03-18 15:09:16 -06:00
|
|
|
And now we can run the program:
|
2008-09-12 17:03:16 -06:00
|
|
|
|
|
|
|
% helloworld3
|
|
|
|
hello, world
|
2009-02-04 16:13:07 -07:00
|
|
|
can't open file; err=No such file or directory
|
2008-09-12 17:03:16 -06:00
|
|
|
%
|
|
|
|
|
2008-09-15 12:48:37 -06:00
|
|
|
Rotting cats
|
|
|
|
----
|
|
|
|
|
2009-03-16 23:53:23 -06:00
|
|
|
Building on the "file" package, here's a simple version of the Unix utility "cat(1)",
|
2009-01-09 16:16:31 -07:00
|
|
|
"progs/cat.go":
|
2008-09-15 12:48:37 -06:00
|
|
|
|
|
|
|
--PROG progs/cat.go
|
|
|
|
|
|
|
|
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
|
2009-03-18 15:09:16 -06:00
|
|
|
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
|
2008-09-15 12:48:37 -06:00
|
|
|
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
|
2008-09-16 12:00:11 -06:00
|
|
|
case expressions don't need to be constants or even integers, as long as
|
|
|
|
they all have the same type.
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2009-01-09 16:16:31 -07:00
|
|
|
Since the "switch" value is just "true", we could leave it off -- as is also
|
|
|
|
the situation
|
2008-09-15 12:48:37 -06:00
|
|
|
in a "for" statement, a missing value means "true". In fact, such a "switch"
|
2009-01-09 16:16:31 -07:00
|
|
|
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".
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2009-03-18 15:09:16 -06:00
|
|
|
Line 21 calls "Write()" by slicing the incoming buffer, which is itself a slice.
|
2009-01-09 16:16:31 -07:00
|
|
|
Slices provide the standard Go way to handle I/O buffers.
|
2008-09-15 12:48:37 -06:00
|
|
|
|
|
|
|
Now let's make a variant of "cat" that optionally does "rot13" on its input.
|
|
|
|
It's easy to do by just processing the bytes, but instead we will exploit
|
|
|
|
Go's notion of an <i>interface</i>.
|
|
|
|
|
2009-03-16 23:53:23 -06:00
|
|
|
The "cat()" subroutine uses only two methods of "f": "Read()" and "String()",
|
2008-09-15 12:48:37 -06:00
|
|
|
so let's start by defining an interface that has exactly those two methods.
|
|
|
|
Here is code from "progs/cat_rot13.go":
|
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
--PROG progs/cat_rot13.go /type.reader/ /^}/
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
Any type that implements the two methods of "reader" -- regardless of whatever
|
2008-09-15 12:48:37 -06:00
|
|
|
other methods the type may also contain -- is said to <i>implement</i> the
|
2009-03-16 23:53:23 -06:00
|
|
|
interface. Since "file.File" implements these methods, it implements the
|
2009-01-20 20:32:36 -07:00
|
|
|
"reader" interface. We could tweak the "cat" subroutine to accept a "reader"
|
2009-03-16 23:53:23 -06:00
|
|
|
instead of a "*file.File" and it would work just fine, but let's embellish a little
|
2009-01-20 20:32:36 -07:00
|
|
|
first by writing a second type that implements "reader", one that wraps an
|
|
|
|
existing "reader" and does "rot13" on the data. To do this, we just define
|
2008-09-15 12:48:37 -06:00
|
|
|
the type and implement the methods and with no other bookkeeping,
|
2009-01-20 20:32:36 -07:00
|
|
|
we have a second implementation of the "reader" interface.
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
--PROG progs/cat_rot13.go /type.rotate13/ /end.of.rotate13/
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2009-03-18 15:09:16 -06:00
|
|
|
(The "rot13" function called on line 38 is trivial and not worth reproducing.)
|
2008-09-15 12:48:37 -06:00
|
|
|
|
|
|
|
To use the new feature, we define a flag:
|
|
|
|
|
|
|
|
--PROG progs/cat_rot13.go /rot13_flag/
|
|
|
|
|
|
|
|
and use it from within a mostly unchanged "cat()" function:
|
|
|
|
|
|
|
|
--PROG progs/cat_rot13.go /func.cat/ /^}/
|
|
|
|
|
2008-09-29 21:06:48 -06:00
|
|
|
(We could also do the wrapping in "main" and leave "cat()" mostly alone, except
|
2009-01-09 16:16:31 -07:00
|
|
|
for changing the type of the argument; consider that an exercise.)
|
2009-03-18 15:09:16 -06:00
|
|
|
Lines 52 through 55 set it all up: If the "rot13" flag is true, wrap the "reader"
|
2009-01-20 20:32:36 -07:00
|
|
|
we received into a "rotate13" and proceed. Note that the interface variables
|
|
|
|
are values, not pointers: the argument is of type "reader", not "*reader",
|
2008-09-15 12:48:37 -06:00
|
|
|
even though under the covers it holds a pointer to a "struct".
|
|
|
|
|
|
|
|
Here it is in action:
|
|
|
|
|
|
|
|
<pre>
|
|
|
|
% echo abcdefghijklmnopqrstuvwxyz | ./cat
|
|
|
|
abcdefghijklmnopqrstuvwxyz
|
|
|
|
% echo abcdefghijklmnopqrstuvwxyz | ./cat --rot13
|
|
|
|
nopqrstuvwxyzabcdefghijklm
|
|
|
|
%
|
|
|
|
</pre>
|
|
|
|
|
|
|
|
Fans of dependency injection may take cheer from how easily interfaces
|
2008-09-29 21:06:48 -06:00
|
|
|
allow us to substitute the implementation of a file descriptor.
|
2008-09-15 12:48:37 -06:00
|
|
|
|
|
|
|
Interfaces are a distinct feature of Go. An interface is implemented by a
|
|
|
|
type if the type implements all the methods declared in the interface.
|
|
|
|
This means
|
|
|
|
that a type may implement an arbitrary number of different interfaces.
|
|
|
|
There is no type hierarchy; things can be much more <i>ad hoc</i>,
|
2009-03-16 23:53:23 -06:00
|
|
|
as we saw with "rot13". The type "file.File" implements "reader"; it could also
|
2009-01-20 20:32:36 -07:00
|
|
|
implement a "writer", or any other interface built from its methods that
|
2008-09-15 12:48:37 -06:00
|
|
|
fits the current situation. Consider the <i>empty interface</i>
|
|
|
|
|
|
|
|
<pre>
|
|
|
|
type interface Empty {}
|
|
|
|
</pre>
|
|
|
|
|
|
|
|
<i>Every</i> type implements the empty interface, which makes it
|
|
|
|
useful for things like containers.
|
|
|
|
|
|
|
|
Sorting
|
|
|
|
----
|
|
|
|
|
2009-02-04 16:13:07 -07:00
|
|
|
Interfaces provide a simple form of polymorphism since they completely
|
|
|
|
separate the definition of what an object does from how it does it, allowing
|
|
|
|
distinct implementations to be represented at different times by the
|
|
|
|
same interface variable.
|
|
|
|
|
|
|
|
As an example, consider this simple sort algorithm taken from "progs/sort.go":
|
2008-09-15 12:48:37 -06:00
|
|
|
|
|
|
|
--PROG progs/sort.go /func.Sort/ /^}/
|
|
|
|
|
|
|
|
The code needs only three methods, which we wrap into "SortInterface":
|
|
|
|
|
|
|
|
--PROG progs/sort.go /interface/ /^}/
|
|
|
|
|
2009-01-09 16:16:31 -07:00
|
|
|
We can apply "Sort" to any type that implements "Len", "Less", and "Swap".
|
2008-09-15 12:48:37 -06:00
|
|
|
The "sort" package includes the necessary methods to allow sorting of
|
2009-01-09 16:16:31 -07:00
|
|
|
arrays of integers, strings, etc.; here's the code for arrays of "int"
|
2008-09-15 12:48:37 -06:00
|
|
|
|
|
|
|
--PROG progs/sort.go /type.*IntArray/ /swap/
|
|
|
|
|
2009-01-09 16:16:31 -07:00
|
|
|
Here we see methods defined for non-"struct" types. You can define methods
|
|
|
|
for any type you define and name in your package.
|
|
|
|
|
2008-09-15 12:48:37 -06:00
|
|
|
And now a routine to test it out, from "progs/sortmain.go". This
|
|
|
|
uses a function in the "sort" package, omitted here for brevity,
|
|
|
|
to test that the result is sorted.
|
|
|
|
|
|
|
|
--PROG progs/sortmain.go /func.ints/ /^}/
|
|
|
|
|
|
|
|
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:
|
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
--PROG progs/sortmain.go /type.day/ /Swap/
|
2009-01-09 16:16:31 -07:00
|
|
|
|
|
|
|
|
|
|
|
Printing
|
|
|
|
---
|
|
|
|
|
|
|
|
The examples of formatted printing so far have been modest. In this section
|
|
|
|
we'll talk about how formatted I/O can be done well in Go.
|
|
|
|
|
2009-03-18 15:09:16 -06:00
|
|
|
We've seen simple uses of the package "fmt", which
|
|
|
|
implements "Printf", "Fprintf", and so on.
|
2009-01-20 20:32:36 -07:00
|
|
|
Within the "fmt" package, "Printf" is declared with this signature:
|
2009-01-09 16:16:31 -07:00
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
Printf(format string, v ...) (n int, errno *os.Error)
|
2009-01-09 16:16:31 -07:00
|
|
|
|
|
|
|
That "..." represents the variadic argument list that in C would
|
|
|
|
be handled using the "stdarg.h" macros, but in Go is passed using
|
|
|
|
an empty interface variable ("interface {}") that is then unpacked
|
|
|
|
using the reflection library. It's off topic here but the use of
|
2009-01-20 20:32:36 -07:00
|
|
|
reflection helps explain some of the nice properties of Go's Printf,
|
|
|
|
due to the ability of "Printf" to discover the type of its arguments
|
2009-01-09 16:16:31 -07:00
|
|
|
dynamically.
|
|
|
|
|
|
|
|
For example, in C each format must correspond to the type of its
|
|
|
|
argument. It's easier in many cases in Go. Instead of "%llud" you
|
2009-01-20 20:32:36 -07:00
|
|
|
can just say "%d"; "Printf" knows the size and signedness of the
|
2009-01-09 16:16:31 -07:00
|
|
|
integer and can do the right thing for you. The snippet
|
|
|
|
|
|
|
|
--PROG progs/print.go 'NR==6' 'NR==7'
|
|
|
|
|
|
|
|
prints
|
|
|
|
|
|
|
|
18446744073709551615 -1
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
--PROG progs/print.go 'NR==10' 'NR==13'
|
|
|
|
|
|
|
|
is
|
|
|
|
|
|
|
|
18446744073709551615 {77 Sunset Strip} [1 2 3 4]
|
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
You can drop the formatting altogether if you use "Print" or "Println"
|
|
|
|
instead of "Printf". Those routines do fully automatic formatting.
|
|
|
|
The "Print" function just prints its elements out using the equivalent
|
|
|
|
of "%v" while "Println" automatically inserts spaces between arguments
|
2009-01-09 16:16:31 -07:00
|
|
|
and adds a newline. The output of each of these two lines is identical
|
2009-01-20 20:32:36 -07:00
|
|
|
to that of the "Printf" call above.
|
2009-01-09 16:16:31 -07:00
|
|
|
|
|
|
|
--PROG progs/print.go 'NR==14' 'NR==15'
|
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
If you have your own type you'd like "Printf" or "Print" to format,
|
2009-01-09 16:16:31 -07:00
|
|
|
just give it a "String()" method that returns a string. The print
|
|
|
|
routines will examine the value to inquire whether it implements
|
|
|
|
the method and if so, use it rather than some other formatting.
|
|
|
|
Here's a simple example.
|
|
|
|
|
|
|
|
--PROG progs/print_string.go 'NR==5' END
|
|
|
|
|
|
|
|
Since "*T" has a "String()" method, the
|
|
|
|
default formatter for that type will use it and produce the output
|
|
|
|
|
|
|
|
77 Sunset Strip
|
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
Observe that the "String()" method calls "Sprint" (the obvious Go
|
|
|
|
variant that returns a string) to do its formatting; special formatters
|
|
|
|
can use the "fmt" library recursively.
|
2009-01-09 16:16:31 -07:00
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
Another feature of "Printf" is that the format "%T" will print a string
|
2009-01-09 16:16:31 -07:00
|
|
|
representation of the type of a value, which can be handy when debugging
|
|
|
|
polymorphic code.
|
|
|
|
|
|
|
|
It's possible to write full custom print formats with flags and precisions
|
|
|
|
and such, but that's getting a little off the main thread so we'll leave it
|
|
|
|
as an exploration exercise.
|
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
You might ask, though, how "Printf" can tell whether a type implements
|
2009-01-09 16:16:31 -07:00
|
|
|
the "String()" method. Actually what it does is ask if the value can
|
|
|
|
be converted to an interface variable that implements the method.
|
|
|
|
Schematically, given a value "v", it does this:
|
|
|
|
|
|
|
|
|
|
|
|
type String interface {
|
|
|
|
String() string
|
|
|
|
}
|
|
|
|
|
|
|
|
s, ok := v.(String); // Test whether v satisfies "String"
|
|
|
|
if ok {
|
|
|
|
result = s.String()
|
|
|
|
} else {
|
|
|
|
result = default_output(v)
|
|
|
|
}
|
|
|
|
|
2009-02-04 16:13:07 -07:00
|
|
|
The code uses a ``type assertion'' ("v.(String)") to test if the value stored in
|
2009-01-09 16:16:31 -07:00
|
|
|
"v" satisfies the "String" interface; if it does, "s"
|
|
|
|
will become an interface variable implementing the method and "ok" will
|
|
|
|
be "true". We then use the interface variable to call the method.
|
|
|
|
(The ''comma, ok'' pattern is a Go idiom used to test the success of
|
|
|
|
operations such as type conversion, map update, communications, and so on,
|
|
|
|
although this is the only appearance in this tutorial.)
|
|
|
|
If the value does not satisfy the interface, "ok" will be false.
|
|
|
|
|
2009-02-04 16:13:07 -07:00
|
|
|
In this snippet "String" is used as both a type name and a method name. This does
|
|
|
|
not create any ambiguity because methods only appear in association
|
|
|
|
with a variable ("s.String()"); a method name can never appear in a context
|
|
|
|
where a type name is legal and vice versa. Another way to say this is that the
|
|
|
|
method "String" is only available within the scope bound to a variable of type
|
|
|
|
"String". We double-use the name because it makes the interface type
|
|
|
|
self-describing ("String" (the interface) implements "String" (the method)).
|
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
One last wrinkle. To complete the suite, besides "Printf" etc. and "Sprintf"
|
|
|
|
etc., there are also "Fprintf" etc. Unlike in C, "Fprintf"'s first argument is
|
2009-01-09 16:16:31 -07:00
|
|
|
not a file. Instead, it is a variable of type "io.Write", which is an
|
|
|
|
interface type defined in the "io" library:
|
|
|
|
|
2009-02-08 11:17:23 -07:00
|
|
|
type Write interface {
|
2009-01-09 16:16:31 -07:00
|
|
|
Write(p []byte) (n int, err *os.Error);
|
|
|
|
}
|
|
|
|
|
2009-02-04 16:13:07 -07:00
|
|
|
(This interface is another doubled name, this time for "Write"; there are also
|
|
|
|
"io.Read", "io.ReadWrite", and so on.)
|
2009-01-20 20:32:36 -07:00
|
|
|
Thus you can call "Fprintf" on any type that implements a standard "Write()"
|
2009-01-09 16:16:31 -07:00
|
|
|
method, not just files but also network channels, buffers, rot13ers, whatever
|
|
|
|
you want.
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2008-09-16 12:00:11 -06:00
|
|
|
Prime numbers
|
2008-09-15 12:48:37 -06:00
|
|
|
----
|
|
|
|
|
2008-09-16 12:00:11 -06:00
|
|
|
Now we come to processes and communication -- concurrent programming.
|
2008-09-15 12:48:37 -06:00
|
|
|
It's a big subject so to be brief we assume some familiarity with the topic.
|
|
|
|
|
2008-09-16 12:00:11 -06:00
|
|
|
A classic program in the style is the prime sieve of Eratosthenes.
|
2009-01-09 16:16:31 -07:00
|
|
|
It works by taking a stream of all the natural numbers and introducing
|
2008-09-16 12:00:11 -06:00
|
|
|
a sequence of filters, one for each prime, to winnow the multiples of
|
|
|
|
that prime. At each step we have a sequence of filters of the primes
|
|
|
|
so far, and the next number to pop out is the next prime, which triggers
|
|
|
|
the creation of the next filter in the chain.
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2008-09-16 12:00:11 -06:00
|
|
|
Here's a flow diagram; each box represents a filter element whose
|
|
|
|
creation is triggered by the first number that flowed from the
|
|
|
|
elements before it.
|
2008-09-15 12:48:37 -06:00
|
|
|
|
|
|
|
<br>
|
|
|
|
|
2008-09-16 12:00:11 -06:00
|
|
|
<img src='sieve.gif'>
|
2008-09-15 12:48:37 -06:00
|
|
|
|
|
|
|
<br>
|
|
|
|
|
|
|
|
To create a stream of integers, we use a Go <i>channel</i>, which,
|
2008-09-16 12:00:11 -06:00
|
|
|
borrowing from CSP's descendants, represents a communications
|
|
|
|
channel that can connect two concurrent computations.
|
2009-01-09 16:16:31 -07:00
|
|
|
In Go, channel variables are references to a run-time object that
|
|
|
|
coordinates the communication; as with maps and slices, use
|
|
|
|
"make" to create a new channel.
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2008-09-16 12:00:11 -06:00
|
|
|
Here is the first function in "progs/sieve.go":
|
|
|
|
|
|
|
|
--PROG progs/sieve.go /Send/ /^}/
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
The "generate" function sends the sequence 2, 3, 4, 5, ... to its
|
2008-09-22 12:29:40 -06:00
|
|
|
argument channel, "ch", using the binary communications operator "<-".
|
2009-02-04 16:13:07 -07:00
|
|
|
Channel operations block, so if there's no recipient for the value on "ch",
|
2008-09-16 12:00:11 -06:00
|
|
|
the send operation will wait until one becomes available.
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
The "filter" function has three arguments: an input channel, an output
|
2008-09-16 12:00:11 -06:00
|
|
|
channel, and a prime number. It copies values from the input to the
|
2008-09-16 20:40:38 -06:00
|
|
|
output, discarding anything divisible by the prime. The unary communications
|
2008-09-16 12:00:11 -06:00
|
|
|
operator "<-" (receive) retrieves the next value on the channel.
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2008-09-16 12:00:11 -06:00
|
|
|
--PROG progs/sieve.go /Copy/ /^}/
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2008-09-16 12:00:11 -06:00
|
|
|
The generator and filters execute concurrently. Go has
|
2008-09-15 12:48:37 -06:00
|
|
|
its own model of process/threads/light-weight processes/coroutines,
|
|
|
|
so to avoid notational confusion we'll call concurrently executing
|
|
|
|
computations in Go <i>goroutines</i>. To start a goroutine,
|
|
|
|
invoke the function, prefixing the call with the keyword "go";
|
2008-09-16 12:00:11 -06:00
|
|
|
this starts the function running in parallel with the current
|
2008-09-15 12:48:37 -06:00
|
|
|
computation but in the same address space:
|
|
|
|
|
|
|
|
go sum(huge_array); // calculate sum in the background
|
|
|
|
|
|
|
|
If you want to know when the calculation is done, pass a channel
|
|
|
|
on which it can report back:
|
|
|
|
|
2009-01-09 16:16:31 -07:00
|
|
|
ch := make(chan int);
|
2008-09-15 12:48:37 -06:00
|
|
|
go sum(huge_array, ch);
|
|
|
|
// ... do something else for a while
|
|
|
|
result := <-ch; // wait for, and retrieve, result
|
|
|
|
|
2008-09-16 12:00:11 -06:00
|
|
|
Back to our prime sieve. Here's how the sieve pipeline is stitched
|
|
|
|
together:
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2008-09-16 12:00:11 -06:00
|
|
|
--PROG progs/sieve.go /func.main/ /^}/
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2009-03-18 15:09:16 -06:00
|
|
|
Line 25 creates the initial channel to pass to "generate", which it
|
2009-01-20 20:32:36 -07:00
|
|
|
then starts up. As each prime pops out of the channel, a new "filter"
|
2008-09-16 12:00:11 -06:00
|
|
|
is added to the pipeline and <i>its</i> output becomes the new value
|
|
|
|
of "ch".
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2008-09-16 12:00:11 -06:00
|
|
|
The sieve program can be tweaked to use a pattern common
|
|
|
|
in this style of programming. Here is a variant version
|
2009-01-20 20:32:36 -07:00
|
|
|
of "generate", from "progs/sieve1.go":
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
--PROG progs/sieve1.go /func.generate/ /^}/
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2008-09-16 12:00:11 -06:00
|
|
|
This version does all the setup internally. It creates the output
|
|
|
|
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.
|
2009-02-04 16:13:07 -07:00
|
|
|
|
2009-03-18 15:09:16 -06:00
|
|
|
The function literal notation (lines 8-12) allows us to construct an
|
2009-02-04 16:13:07 -07:00
|
|
|
anonymous function and invoke it on the spot.
|
|
|
|
|
|
|
|
The same change can be made to "filter":
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
--PROG progs/sieve1.go /func.filter/ /^}/
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
The "sieve" function's main loop becomes simpler and clearer as a
|
2008-09-16 12:00:11 -06:00
|
|
|
result, and while we're at it let's turn it into a factory too:
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
--PROG progs/sieve1.go /func.sieve/ /^}/
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2008-09-16 12:00:11 -06:00
|
|
|
Now "main"'s interface to the prime sieve is a channel of primes:
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2008-09-16 12:00:11 -06:00
|
|
|
--PROG progs/sieve1.go /func.main/ /^}/
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2008-09-16 14:14:44 -06:00
|
|
|
Multiplexing
|
2008-09-16 12:00:11 -06:00
|
|
|
----
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2008-09-16 14:14:44 -06:00
|
|
|
With channels, it's possible to serve multiple independent client goroutines without
|
|
|
|
writing an actual multiplexer. The trick is to send the server a channel in the message,
|
|
|
|
which it will then use to reply to the original sender.
|
|
|
|
A realistic client-server program is a lot of code, so here is a very simple substitute
|
2009-01-30 11:18:58 -07:00
|
|
|
to illustrate the idea. It starts by defining a "request" type, which embeds a channel
|
2008-09-16 14:14:44 -06:00
|
|
|
that will be used for the reply.
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
--PROG progs/server.go /type.request/ /^}/
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2008-09-16 14:14:44 -06:00
|
|
|
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:
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
--PROG progs/server.go /type.binOp/ /^}/
|
2008-09-15 12:48:37 -06:00
|
|
|
|
2009-03-18 15:09:16 -06:00
|
|
|
Line 10 defines the name "binOp" to be a function taking two integers and
|
2009-01-09 16:16:31 -07:00
|
|
|
returning a third.
|
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
The "server" routine loops forever, receiving requests and, to avoid blocking due to
|
2008-09-16 14:14:44 -06:00
|
|
|
a long-running operation, starting a goroutine to do the actual work.
|
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
--PROG progs/server.go /func.server/ /^}/
|
2008-09-16 14:14:44 -06:00
|
|
|
|
|
|
|
We construct a server in a familiar way, starting it up and returning a channel to
|
|
|
|
connect to it:
|
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
--PROG progs/server.go /func.startServer/ /^}/
|
2008-09-16 14:14:44 -06:00
|
|
|
|
|
|
|
Here's a simple test. It starts a server with an addition operator, and sends out
|
|
|
|
lots of requests but doesn't wait for the reply. Only after all the requests are sent
|
|
|
|
does it check the results.
|
|
|
|
|
|
|
|
--PROG progs/server.go /func.main/ /^}/
|
|
|
|
|
|
|
|
One annoyance with this program is that it doesn't exit cleanly; when "main" returns
|
|
|
|
there are a number of lingering goroutines blocked on communication. To solve this,
|
2009-01-09 16:16:31 -07:00
|
|
|
we can provide a second, "quit" channel to the server:
|
2008-09-16 14:14:44 -06:00
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
--PROG progs/server1.go /func.startServer/ /^}/
|
2008-09-16 14:14:44 -06:00
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
It passes the quit channel to the "server" function, which uses it like this:
|
2008-09-16 14:14:44 -06:00
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
--PROG progs/server1.go /func.server/ /^}/
|
2008-09-16 14:14:44 -06:00
|
|
|
|
2009-01-20 20:32:36 -07:00
|
|
|
Inside "server", a "select" statement chooses which of the multiple communications
|
2008-09-16 14:14:44 -06:00
|
|
|
listed by its cases can proceed. If all are blocked, it waits until one can proceed; if
|
|
|
|
multiple can proceed, it chooses one at random. In this instance, the "select" allows
|
|
|
|
the server to honor requests until it receives a quit message, at which point it
|
2008-09-16 20:40:38 -06:00
|
|
|
returns, terminating its execution.
|
2008-09-16 14:14:44 -06:00
|
|
|
|
|
|
|
|
|
|
|
All that's left is to strobe the "quit" channel
|
|
|
|
at the end of main:
|
|
|
|
|
|
|
|
--PROG progs/server1.go /adder,.quit/
|
|
|
|
...
|
|
|
|
--PROG progs/server1.go /quit....true/
|
|
|
|
|
|
|
|
There's a lot more to Go programming and concurrent programming in general but this
|
|
|
|
quick tour should give you some of the basics.
|