Rob Pike | 6693730 | 2008-09-12 16:03:16 -0700 | [diff] [blame] | 1 | Let's Go |
Rob Pike | ae4123f | 2008-09-10 11:46:05 -0700 | [diff] [blame] | 2 | ---- |
| 3 | |
| 4 | Rob Pike |
| 5 | |
| 6 | ---- |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 7 | (January 20, 2009) |
Rob Pike | ae4123f | 2008-09-10 11:46:05 -0700 | [diff] [blame] | 8 | |
| 9 | |
| 10 | This document is a tutorial introduction to the basics of the Go systems programming |
Rob Pike | 27a5617 | 2008-09-10 17:11:04 -0700 | [diff] [blame] | 11 | language, intended for programmers familiar with C or C++. It is not a comprehensive |
Rob Pike | 6693730 | 2008-09-12 16:03:16 -0700 | [diff] [blame] | 12 | guide to the language; at the moment the document closest to that is the draft |
| 13 | specification: |
Rob Pike | 27a5617 | 2008-09-10 17:11:04 -0700 | [diff] [blame] | 14 | |
Ian Lance Taylor | 128f052 | 2008-09-22 11:29:40 -0700 | [diff] [blame] | 15 | /doc/go_spec.html |
Rob Pike | 27a5617 | 2008-09-10 17:11:04 -0700 | [diff] [blame] | 16 | |
| 17 | To check out the compiler and tools and be ready to run Go programs, see |
| 18 | |
| 19 | /doc/go_setup.html |
| 20 | |
| 21 | The presentation proceeds through a series of modest programs to illustrate |
| 22 | key features of the language. All the programs work (at time of writing) and are |
| 23 | checked in at |
| 24 | |
| 25 | /doc/progs |
| 26 | |
| 27 | Program snippets are annotated with the line number in the original file; for |
| 28 | cleanliness, blank lines remain blank. |
| 29 | |
| 30 | Hello, World |
| 31 | ---- |
| 32 | |
| 33 | Let's start in the usual way: |
Rob Pike | ae4123f | 2008-09-10 11:46:05 -0700 | [diff] [blame] | 34 | |
| 35 | --PROG progs/helloworld.go |
| 36 | |
Rob Pike | 27a5617 | 2008-09-10 17:11:04 -0700 | [diff] [blame] | 37 | Every Go source file declares which package it's part of using a "package" statement. |
| 38 | The "main" package's "main" function is where the program starts running (after |
| 39 | any initialization). |
Rob Pike | ae4123f | 2008-09-10 11:46:05 -0700 | [diff] [blame] | 40 | |
Rob Pike | 27a5617 | 2008-09-10 17:11:04 -0700 | [diff] [blame] | 41 | Function declarations are introduced with the "func" keyword. |
Rob Pike | ae4123f | 2008-09-10 11:46:05 -0700 | [diff] [blame] | 42 | |
Rob Pike | 27a5617 | 2008-09-10 17:11:04 -0700 | [diff] [blame] | 43 | Notice that string constants can contain Unicode characters, encoded in UTF-8. |
| 44 | Go is defined to accept UTF-8 input. Strings are arrays of bytes, usually used |
| 45 | to store Unicode strings represented in UTF-8. |
Rob Pike | ae4123f | 2008-09-10 11:46:05 -0700 | [diff] [blame] | 46 | |
Rob Pike | 27a5617 | 2008-09-10 17:11:04 -0700 | [diff] [blame] | 47 | The built-in function "print()" has been used during the early stages of |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 48 | development of the language but is not guaranteed to last. Here's a version of the |
Rob Pike | c7ebfed | 2008-09-11 10:21:02 -0700 | [diff] [blame] | 49 | program that doesn't depend on "print()": |
Rob Pike | 27a5617 | 2008-09-10 17:11:04 -0700 | [diff] [blame] | 50 | |
| 51 | --PROG progs/helloworld2.go |
| 52 | |
| 53 | This version imports the ''os'' package to acess its "Stdout" variable, of type |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 54 | "*os.FD". The "import" statement is a declaration: it names the identifier ("os") |
Rob Pike | 6820196 | 2008-09-16 13:14:44 -0700 | [diff] [blame] | 55 | that will be used to access members of the package imported from the file ("os"), |
| 56 | found in the current directory or in a standard location. |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 57 | Given "os.Stdout" we can use its "WriteString" method to print the string. |
Rob Pike | 27a5617 | 2008-09-10 17:11:04 -0700 | [diff] [blame] | 58 | |
| 59 | The comment convention is the same as in C++: |
| 60 | |
| 61 | /* ... */ |
| 62 | // ... |
| 63 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 64 | Later we'll have much more to say about printing. |
| 65 | |
Rob Pike | 27a5617 | 2008-09-10 17:11:04 -0700 | [diff] [blame] | 66 | Echo |
| 67 | ---- |
| 68 | |
| 69 | Next up, here's a version of the Unix utility "echo(1)": |
| 70 | |
| 71 | --PROG progs/echo.go |
| 72 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 73 | This program is small but it's doing a number of new things. In the last example, |
Rob Pike | 27a5617 | 2008-09-10 17:11:04 -0700 | [diff] [blame] | 74 | we saw "func" introducing a function. The keywords "var", "const", and "type" |
| 75 | (not used yet) also introduce declarations, as does "import". |
| 76 | Notice that we can group declarations of the same sort into |
| 77 | parenthesized, semicolon-separated lists if we want, as on lines 3-6 and 10-13. |
| 78 | But it's not necessary to do so; we could have said |
| 79 | |
| 80 | const Space = " " |
| 81 | const Newline = "\n" |
| 82 | |
| 83 | Semicolons aren't needed here; in fact, semicolons are unnecessary after any |
| 84 | top-level declaration, even though they are needed as separators <i>within</i> |
| 85 | a parenthesized list of declarations. |
| 86 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 87 | Also notice that we've dropped the explicit name from the imports; by default, |
| 88 | packages are imported using the name defined by the imported package, |
| 89 | which by convention is of course the file name itself. You can specify your |
| 90 | own import names if you want but it's only necessary if you need to resolve |
| 91 | a naming conflict. |
| 92 | |
| 93 | Having imported the "flag" package, line 8 creates a global variable to hold |
| 94 | the value of echo's "-n" flag. The variable "n_flag" has type "*bool", pointer |
| 95 | to "bool". |
Rob Pike | 27a5617 | 2008-09-10 17:11:04 -0700 | [diff] [blame] | 96 | |
| 97 | In "main.main", we parse the arguments (line 16) and then create a local |
| 98 | string variable we will use to build the output. |
| 99 | |
| 100 | The declaration statement has the form |
| 101 | |
| 102 | var s string = ""; |
| 103 | |
| 104 | This is the "var" keyword, followed by the name of the variable, followed by |
| 105 | its type, followed by an equals sign and an initial value for the variable. |
| 106 | |
| 107 | Go tries to be terse, and this declaration could be shortened. Since the |
| 108 | string constant is of type string, we don't have to tell the compiler that. |
| 109 | We could write |
| 110 | |
| 111 | var s = ""; |
| 112 | |
| 113 | or we could go even shorter and write the idiom |
| 114 | |
| 115 | s := ""; |
| 116 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 117 | The ":=" operator is used a lot in Go to represent an initializing declaration. |
| 118 | (For those who know Limbo, its ":=" construct is the same, but notice |
| 119 | that Go has no colon after the name in a full "var" declaration. |
| 120 | Also, for simplicity of parsing, ":=" only works inside functions, not at |
| 121 | the top level.) |
| 122 | There's one in the "for" clause on the next line: |
Rob Pike | 27a5617 | 2008-09-10 17:11:04 -0700 | [diff] [blame] | 123 | |
| 124 | --PROG progs/echo.go /for/ |
| 125 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 126 | The "flag" package has parsed the arguments and left the non-flag arguments |
Rob Pike | c7ebfed | 2008-09-11 10:21:02 -0700 | [diff] [blame] | 127 | in a list that can be iterated over in the obvious way. |
Rob Pike | 27a5617 | 2008-09-10 17:11:04 -0700 | [diff] [blame] | 128 | |
| 129 | The Go "for" statement differs from that of C in a number of ways. First, |
| 130 | it's the only looping construct; there is no "while" or "do". Second, |
| 131 | there are no parentheses on the clause, but the braces on the body |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 132 | are mandatory. The same applies to the "if" and "switch" statements. |
| 133 | Later examples will show some other ways "for" can be written. |
Rob Pike | 27a5617 | 2008-09-10 17:11:04 -0700 | [diff] [blame] | 134 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 135 | The body of the loop builds up the string "s" by appending (using "+=") |
Rob Pike | 27a5617 | 2008-09-10 17:11:04 -0700 | [diff] [blame] | 136 | the flags and separating spaces. After the loop, if the "-n" flag is not |
| 137 | set, it appends a newline, and then writes the result. |
| 138 | |
| 139 | Notice that "main.main" is a niladic function with no return type. |
| 140 | It's defined that way. Falling off the end of "main.main" means |
| 141 | ''success''; if you want to signal erroneous return, use |
| 142 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 143 | sys.Exit(1) |
Rob Pike | 27a5617 | 2008-09-10 17:11:04 -0700 | [diff] [blame] | 144 | |
| 145 | The "sys" package is built in and contains some essentials for getting |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 146 | started; for instance, "sys.Args" is an array used by the |
| 147 | "flag" package to access the command-line arguments. |
Rob Pike | 27a5617 | 2008-09-10 17:11:04 -0700 | [diff] [blame] | 148 | |
Rob Pike | c7ebfed | 2008-09-11 10:21:02 -0700 | [diff] [blame] | 149 | An Interlude about Types |
| 150 | ---- |
| 151 | |
| 152 | Go has some familiar types such as "int" and "float", which represent |
| 153 | values of the ''appropriate'' size for the machine. It also defines |
| 154 | specifically-sized types such as "int8", "float64", and so on, plus |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 155 | unsigned integer types such as "uint", "uint32", etc. These are |
| 156 | distinct types; even if "int" and "int32" are both 32 bits in size, |
| 157 | they are not the same type. There is also a "byte" synonym for |
| 158 | "uint8", which is the element type for strings. |
Rob Pike | c7ebfed | 2008-09-11 10:21:02 -0700 | [diff] [blame] | 159 | |
| 160 | Speaking of "string", that's a built-in type as well. Strings are |
| 161 | <i>immutable values</i> -- they are not just arrays of "byte" values. |
| 162 | Once you've built a string <i>value</i>, you can't change it, although |
| 163 | of course you can change a string <i>variable</i> simply by |
| 164 | reassigning it. This snippet from "strings.go" is legal code: |
| 165 | |
| 166 | --PROG progs/strings.go /hello/ /ciao/ |
| 167 | |
| 168 | However the following statements are illegal because they would modify |
| 169 | a "string" value: |
| 170 | |
| 171 | s[0] = 'x'; |
| 172 | (*p)[1] = 'y'; |
| 173 | |
| 174 | In C++ terms, Go strings are a bit like "const strings", while pointers |
| 175 | to strings are analogous to "const string" references. |
| 176 | |
| 177 | Yes, there are pointers. However, Go simplifies their use a little; |
| 178 | read on. |
| 179 | |
| 180 | Arrays are declared like this: |
| 181 | |
| 182 | var array_of_int [10]int; |
| 183 | |
| 184 | Arrays, like strings, are values, but they are mutable. This differs |
| 185 | from C, in which "array_of_int" would be usable as a pointer to "int". |
| 186 | In Go, since arrays are values, it's meaningful (and useful) to talk |
| 187 | about pointers to arrays. |
| 188 | |
| 189 | The size of the array is part of its type; however, one can declare |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 190 | a <i>slice</i> variable, to which one can assign any array value |
| 191 | with the same element type. Slices look a lot like arrays but have |
| 192 | no explicit size ("[]" vs. "[10]") and they reference a segment of |
| 193 | an underlying, often anonymous, regular array. Multiple slices |
| 194 | can share data if they represent pieces of the same array; |
| 195 | multiple arrays can never share data. |
| 196 | |
| 197 | Slices are actually much more common in Go programs than |
| 198 | regular arrays; they're more flexible, have reference semantics, |
| 199 | and are efficient. What they lack is the precise control of storage |
| 200 | layout of a regular array; if you want to have a hundred elements |
| 201 | of an array stored within your structure, you should use a regular |
| 202 | array. |
| 203 | |
| 204 | When passing an array to a function, you almost always want |
| 205 | to declare the formal parameter to be a slice. Go will automatically |
| 206 | create (efficiently) a slice reference and pass that. |
| 207 | |
| 208 | Using slices one can write this function (from "sum.go"): |
Rob Pike | c7ebfed | 2008-09-11 10:21:02 -0700 | [diff] [blame] | 209 | |
| 210 | --PROG progs/sum.go /sum/ /^}/ |
| 211 | |
| 212 | and invoke it like this: |
| 213 | |
| 214 | --PROG progs/sum.go /1,2,3/ |
| 215 | |
| 216 | Note how the return type ("int") is defined for "sum()" by stating it |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 217 | after the parameter list. |
| 218 | The expression "[3]int{1,2,3}" -- a type followed by a brace-bounded expression |
| 219 | -- is a constructor for a value, in this case an array of 3 "ints". We pass it |
| 220 | to "sum()" by (automatically) promoting it to a slice. |
Rob Pike | c7ebfed | 2008-09-11 10:21:02 -0700 | [diff] [blame] | 221 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 222 | If you are creating a regular array but want the compiler to count the |
| 223 | elements for you, use "..." as the array size: |
| 224 | |
| 225 | s := sum([...]int{1,2,3}); |
| 226 | |
| 227 | In practice, though, unless you're meticulous about storage layout within a |
| 228 | data structure, a slice - using empty brackets - is all you need: |
| 229 | |
| 230 | s := sum([]int{1,2,3}); |
| 231 | |
| 232 | There are also maps, which you can initialize like this: |
Rob Pike | c7ebfed | 2008-09-11 10:21:02 -0700 | [diff] [blame] | 233 | |
| 234 | m := map[string] int {"one":1 , "two":2} |
| 235 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 236 | The built-in function "len()", which returns number of elements, |
| 237 | makes its first appearance in "sum". It works on strings, arrays, |
| 238 | slices, and maps. |
Rob Pike | c7ebfed | 2008-09-11 10:21:02 -0700 | [diff] [blame] | 239 | |
Rob Pike | c7ebfed | 2008-09-11 10:21:02 -0700 | [diff] [blame] | 240 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 241 | An Interlude about Allocation |
| 242 | ---- |
Rob Pike | c7ebfed | 2008-09-11 10:21:02 -0700 | [diff] [blame] | 243 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 244 | Most types in Go are values. If you have an "int" or a "struct" |
| 245 | or an array, assignment |
| 246 | copies the contents of the object. To allocate something on the stack, |
| 247 | just declare a variable. To allocate it on the heap, use "new()", which |
| 248 | returns a pointer to the allocated storage. |
| 249 | |
| 250 | type T struct { a, b int } |
| 251 | var t *T = new(T); |
| 252 | |
| 253 | or the more idiomatic |
| 254 | |
| 255 | t := new(T); |
| 256 | |
| 257 | Some types - maps, slices, and channels (see below) have reference semantics. |
| 258 | If you're holding a slice or a map and you modify its contents, other variables |
| 259 | referencing the same underlying data will see the modification. If you allocate |
| 260 | a reference object with "new()" you receive a pointer to an uninitialized ("nil") |
| 261 | reference. Instead, for these three types you want to use "make()": |
| 262 | |
| 263 | m := make(map[string] int); |
| 264 | |
| 265 | This statement initializes a new map ready to store entries. If you just declare |
| 266 | the map, as in |
| 267 | |
| 268 | var m map[string] int; |
| 269 | |
| 270 | it is a "nil" reference that cannot hold anything. To use the map, |
| 271 | you must first initialize the reference using "make()" or by assignment to an |
| 272 | existing map. |
| 273 | |
| 274 | Note that "new(T)" returns type "*T" while "make(T)" returns type "T". |
Rob Pike | c7ebfed | 2008-09-11 10:21:02 -0700 | [diff] [blame] | 275 | |
| 276 | An Interlude about Constants |
| 277 | ---- |
| 278 | |
| 279 | Although integers come in lots of sizes in Go, integer constants do not. |
| 280 | There are no constants like "0ll" or "0x0UL". Instead, integer |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 281 | constants are evaluated as ideal, large-precision values that |
| 282 | can overflow only when they are assigned to an integer variable with |
| 283 | too little precision to represent the value. |
Rob Pike | c7ebfed | 2008-09-11 10:21:02 -0700 | [diff] [blame] | 284 | |
| 285 | const hard_eight = (1 << 100) >> 97 // legal |
| 286 | |
| 287 | There are nuances that deserve redirection to the legalese of the |
| 288 | language specification but here are some illustrative examples: |
| 289 | |
| 290 | var a uint64 = 0 // a has type uint64, value 0 |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 291 | a := uint64(0) // equivalent; use a "conversion" |
Rob Pike | c7ebfed | 2008-09-11 10:21:02 -0700 | [diff] [blame] | 292 | i := 0x1234 // i gets default type: int |
| 293 | var j int = 1e6 // legal - 1000000 is representable in an int |
| 294 | x := 1.5 // a float |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 295 | i3div2 := 3/2 // integer division - result is 1 |
| 296 | f3div2 := 3./2. // floating point division - result is 1.5 |
Rob Pike | c7ebfed | 2008-09-11 10:21:02 -0700 | [diff] [blame] | 297 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 298 | Conversions only work for simple cases such as converting "ints" of one |
| 299 | sign or size to another, and between "ints" and "floats", plus a few other |
| 300 | simple cases. There are no automatic numeric conversions of any kind in Go, |
Rob Pike | c7ebfed | 2008-09-11 10:21:02 -0700 | [diff] [blame] | 301 | other than that of making constants have concrete size and type when |
| 302 | assigned to a variable. |
Rob Pike | 6693730 | 2008-09-12 16:03:16 -0700 | [diff] [blame] | 303 | |
| 304 | An I/O Package |
| 305 | ---- |
| 306 | |
| 307 | Next we'll look at a simple package for doing file I/O with the usual |
| 308 | sort of open/close/read/write interface. Here's the start of "fd.go": |
| 309 | |
| 310 | --PROG progs/fd.go /package/ /^}/ |
| 311 | |
| 312 | The first line declares the name of the package -- "fd" for ''file descriptor'' -- |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 313 | and then we import two packages. The "os" package hides the differences |
| 314 | between various operating systems to give a consistent view of files and |
| 315 | so on; here we're only going to use its error handling utilities |
| 316 | and reproduce the rudiments of its file I/O. |
| 317 | |
| 318 | The other item is the low-level, external "syscall" package, which provides |
Rob Pike | 6693730 | 2008-09-12 16:03:16 -0700 | [diff] [blame] | 319 | a primitive interface to the underlying operating system's calls. |
| 320 | |
| 321 | Next is a type definition: the "type" keyword introduces a type declaration, |
| 322 | in this case a data structure called "FD". |
| 323 | To make things a little more interesting, our "FD" includes the name of the file |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 324 | that the file descriptor refers to. |
Rob Pike | 6693730 | 2008-09-12 16:03:16 -0700 | [diff] [blame] | 325 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 326 | Because "FD" starts with a capital letter, the type is available outside the package, |
| 327 | that is, by users of the package. In Go the rule about visibility of information is |
| 328 | simple: if a name (of a top-level type, function, method, constant, variable, or of |
| 329 | a structure field) is capitalized, users of the package may see it. Otherwise, the |
| 330 | name and hence the thing being named is visible only inside the package in which |
| 331 | it is declared. In Go, the term for publicly visible names is ''exported''. |
Rob Pike | 6693730 | 2008-09-12 16:03:16 -0700 | [diff] [blame] | 332 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 333 | In the case of "FD", all its fields are lower case and so invisible to users, but we |
| 334 | will soon give it some exported, upper-case methods. |
| 335 | |
| 336 | First, though, here is a factory to create them: |
| 337 | |
| 338 | --PROG progs/fd.go /newFD/ /^}/ |
Rob Pike | 6693730 | 2008-09-12 16:03:16 -0700 | [diff] [blame] | 339 | |
| 340 | This returns a pointer to a new "FD" structure with the file descriptor and name |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 341 | filled in. This code uses Go's notion of a ''composite literal'', analogous to |
| 342 | the ones used to build maps and arrays, to construct the object. We could write |
| 343 | |
| 344 | n := new(FD); |
| 345 | n.fildes = fd; |
| 346 | n.name = name; |
| 347 | return n |
| 348 | |
| 349 | but for simple structures like "FD" it's easier to return the address of a nonce |
| 350 | composite literal, as is done here on line 17. |
| 351 | |
| 352 | We can use the factory to construct some familiar, exported variables of type "*FD": |
Rob Pike | 6693730 | 2008-09-12 16:03:16 -0700 | [diff] [blame] | 353 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 354 | --PROG progs/fd.go /var/ /^.$/ |
Rob Pike | 6693730 | 2008-09-12 16:03:16 -0700 | [diff] [blame] | 355 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 356 | The "newFD" function was not exported because it's internal. The proper, |
| 357 | exported factory to use is "Open": |
Rob Pike | 6693730 | 2008-09-12 16:03:16 -0700 | [diff] [blame] | 358 | |
| 359 | --PROG progs/fd.go /func.Open/ /^}/ |
| 360 | |
| 361 | There are a number of new things in these few lines. First, "Open" returns |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 362 | multiple values, an "FD" and an error (more about errors in a moment). |
| 363 | We declare the |
| 364 | multi-value return as a parenthesized list of declarations; syntactically |
| 365 | they look just like a second parameter list. The function |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 366 | "syscall.Open" |
Rob Pike | 6693730 | 2008-09-12 16:03:16 -0700 | [diff] [blame] | 367 | also has a multi-value return, which we can grab with the multi-variable |
| 368 | declaration on line 27; it declares "r" and "e" to hold the two values, |
| 369 | both of type "int64" (although you'd have to look at the "syscall" package |
| 370 | to see that). Finally, line 28 returns two values: a pointer to the new "FD" |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 371 | and the error. If "syscall.Open" fails, the file descriptor "r" will |
Rob Pike | 6693730 | 2008-09-12 16:03:16 -0700 | [diff] [blame] | 372 | be negative and "NewFD" will return "nil". |
| 373 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 374 | About those errors: The "os" library includes a general notion of an error |
| 375 | string, maintaining a unique set of errors throughout the program. It's a |
| 376 | good idea to use its facility in your own interfaces, as we do here, for |
| 377 | consistent error handling throughout Go code. In "Open" we use the |
| 378 | routine "os.ErrnoToError" to translate Unix's integer "errno" value into |
| 379 | an error string, which will be stored in a unique instance of "*os.Error". |
| 380 | |
| 381 | Now that we can build "FDs", we can write methods for them. To declare |
Rob Pike | 6693730 | 2008-09-12 16:03:16 -0700 | [diff] [blame] | 382 | a method of a type, we define a function to have an explicit receiver |
| 383 | of that type, placed |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 384 | in parentheses before the function name. Here are some methods for "*FD", |
Rob Pike | 6693730 | 2008-09-12 16:03:16 -0700 | [diff] [blame] | 385 | each of which declares a receiver variable "fd". |
| 386 | |
| 387 | --PROG progs/fd.go /Close/ END |
| 388 | |
| 389 | There is no implicit "this" and the receiver variable must be used to access |
| 390 | members of the structure. Methods are not declared within |
| 391 | the "struct" declaration itself. The "struct" declaration defines only data members. |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 392 | In fact, methods can be created for any type you name, such as an integer or |
| 393 | array, not just for "structs". We'll see an an example with arrays later. |
| 394 | |
| 395 | These methods use the public variable "os.EINVAL" to return the ("*os.Error" |
| 396 | version of the) Unix error code EINVAL. The "os" library defines a standard |
| 397 | set of such error values. |
Rob Pike | 6693730 | 2008-09-12 16:03:16 -0700 | [diff] [blame] | 398 | |
| 399 | Finally, we can use our new package: |
| 400 | |
| 401 | --PROG progs/helloworld3.go |
| 402 | |
| 403 | and run the program: |
| 404 | |
| 405 | % helloworld3 |
| 406 | hello, world |
| 407 | can't open file; errno=2 |
| 408 | % |
| 409 | |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 410 | Rotting cats |
| 411 | ---- |
| 412 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 413 | Building on the "fd" package, here's a simple version of the Unix utility "cat(1)", |
| 414 | "progs/cat.go": |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 415 | |
| 416 | --PROG progs/cat.go |
| 417 | |
| 418 | By now this should be easy to follow, but the "switch" statement introduces some |
| 419 | new features. Like a "for" loop, an "if" or "switch" can include an |
| 420 | initialization statement. The "switch" on line 12 uses one to create variables |
| 421 | "nr" and "er" to hold the return values from "fd.Read()". (The "if" on line 19 |
| 422 | has the same idea.) The "switch" statement is general: it evaluates the cases |
| 423 | from top to bottom looking for the first case that matches the value; the |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 424 | case expressions don't need to be constants or even integers, as long as |
| 425 | they all have the same type. |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 426 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 427 | Since the "switch" value is just "true", we could leave it off -- as is also |
| 428 | the situation |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 429 | in a "for" statement, a missing value means "true". In fact, such a "switch" |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 430 | is a form of "if-else" chain. While we're here, it should be mentioned that in |
| 431 | "switch" statements each "case" has an implicit "break". |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 432 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 433 | Line 19 calls "Write()" by slicing the incoming buffer, which is itself a slice. |
| 434 | Slices provide the standard Go way to handle I/O buffers. |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 435 | |
| 436 | Now let's make a variant of "cat" that optionally does "rot13" on its input. |
| 437 | It's easy to do by just processing the bytes, but instead we will exploit |
| 438 | Go's notion of an <i>interface</i>. |
| 439 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 440 | The "cat()" subroutine uses only two methods of "fd": "Read()" and "String()", |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 441 | so let's start by defining an interface that has exactly those two methods. |
| 442 | Here is code from "progs/cat_rot13.go": |
| 443 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 444 | --PROG progs/cat_rot13.go /type.reader/ /^}/ |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 445 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 446 | Any type that implements the two methods of "reader" -- regardless of whatever |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 447 | other methods the type may also contain -- is said to <i>implement</i> the |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 448 | interface. Since "fd.FD" implements these methods, it implements the |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 449 | "reader" interface. We could tweak the "cat" subroutine to accept a "reader" |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 450 | instead of a "*fd.FD" and it would work just fine, but let's embellish a little |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 451 | first by writing a second type that implements "reader", one that wraps an |
| 452 | existing "reader" and does "rot13" on the data. To do this, we just define |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 453 | the type and implement the methods and with no other bookkeeping, |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 454 | we have a second implementation of the "reader" interface. |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 455 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 456 | --PROG progs/cat_rot13.go /type.rotate13/ /end.of.rotate13/ |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 457 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 458 | (The "rot13" function called on line 37 is trivial and not worth reproducing.) |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 459 | |
| 460 | To use the new feature, we define a flag: |
| 461 | |
| 462 | --PROG progs/cat_rot13.go /rot13_flag/ |
| 463 | |
| 464 | and use it from within a mostly unchanged "cat()" function: |
| 465 | |
| 466 | --PROG progs/cat_rot13.go /func.cat/ /^}/ |
| 467 | |
Rob Pike | 81672ef | 2008-09-29 20:06:48 -0700 | [diff] [blame] | 468 | (We could also do the wrapping in "main" and leave "cat()" mostly alone, except |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 469 | for changing the type of the argument; consider that an exercise.) |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 470 | Lines 51 through 53 set it all up: If the "rot13" flag is true, wrap the "reader" |
| 471 | we received into a "rotate13" and proceed. Note that the interface variables |
| 472 | are values, not pointers: the argument is of type "reader", not "*reader", |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 473 | even though under the covers it holds a pointer to a "struct". |
| 474 | |
| 475 | Here it is in action: |
| 476 | |
| 477 | <pre> |
| 478 | % echo abcdefghijklmnopqrstuvwxyz | ./cat |
| 479 | abcdefghijklmnopqrstuvwxyz |
| 480 | % echo abcdefghijklmnopqrstuvwxyz | ./cat --rot13 |
| 481 | nopqrstuvwxyzabcdefghijklm |
| 482 | % |
| 483 | </pre> |
| 484 | |
| 485 | Fans of dependency injection may take cheer from how easily interfaces |
Rob Pike | 81672ef | 2008-09-29 20:06:48 -0700 | [diff] [blame] | 486 | allow us to substitute the implementation of a file descriptor. |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 487 | |
| 488 | Interfaces are a distinct feature of Go. An interface is implemented by a |
| 489 | type if the type implements all the methods declared in the interface. |
| 490 | This means |
| 491 | that a type may implement an arbitrary number of different interfaces. |
| 492 | There is no type hierarchy; things can be much more <i>ad hoc</i>, |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 493 | as we saw with "rot13". The type "fd.FD" implements "reader"; it could also |
| 494 | implement a "writer", or any other interface built from its methods that |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 495 | fits the current situation. Consider the <i>empty interface</i> |
| 496 | |
| 497 | <pre> |
| 498 | type interface Empty {} |
| 499 | </pre> |
| 500 | |
| 501 | <i>Every</i> type implements the empty interface, which makes it |
| 502 | useful for things like containers. |
| 503 | |
| 504 | Sorting |
| 505 | ---- |
| 506 | |
| 507 | As another example of interfaces, consider this simple sort algorithm, |
| 508 | taken from "progs/sort.go": |
| 509 | |
| 510 | --PROG progs/sort.go /func.Sort/ /^}/ |
| 511 | |
| 512 | The code needs only three methods, which we wrap into "SortInterface": |
| 513 | |
| 514 | --PROG progs/sort.go /interface/ /^}/ |
| 515 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 516 | We can apply "Sort" to any type that implements "Len", "Less", and "Swap". |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 517 | The "sort" package includes the necessary methods to allow sorting of |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 518 | arrays of integers, strings, etc.; here's the code for arrays of "int" |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 519 | |
| 520 | --PROG progs/sort.go /type.*IntArray/ /swap/ |
| 521 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 522 | Here we see methods defined for non-"struct" types. You can define methods |
| 523 | for any type you define and name in your package. |
| 524 | |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 525 | And now a routine to test it out, from "progs/sortmain.go". This |
| 526 | uses a function in the "sort" package, omitted here for brevity, |
| 527 | to test that the result is sorted. |
| 528 | |
| 529 | --PROG progs/sortmain.go /func.ints/ /^}/ |
| 530 | |
| 531 | If we have a new type we want to be able to sort, all we need to do is |
| 532 | to implement the three methods for that type, like this: |
| 533 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 534 | --PROG progs/sortmain.go /type.day/ /Swap/ |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 535 | |
| 536 | |
| 537 | Printing |
| 538 | --- |
| 539 | |
| 540 | The examples of formatted printing so far have been modest. In this section |
| 541 | we'll talk about how formatted I/O can be done well in Go. |
| 542 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 543 | There's a package "fmt" that implements a version of "Printf" (upper case) |
| 544 | that should look familiar: |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 545 | |
| 546 | --PROG progs/printf.go |
| 547 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 548 | Within the "fmt" package, "Printf" is declared with this signature: |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 549 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 550 | Printf(format string, v ...) (n int, errno *os.Error) |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 551 | |
| 552 | That "..." represents the variadic argument list that in C would |
| 553 | be handled using the "stdarg.h" macros, but in Go is passed using |
| 554 | an empty interface variable ("interface {}") that is then unpacked |
| 555 | using the reflection library. It's off topic here but the use of |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 556 | reflection helps explain some of the nice properties of Go's Printf, |
| 557 | due to the ability of "Printf" to discover the type of its arguments |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 558 | dynamically. |
| 559 | |
| 560 | For example, in C each format must correspond to the type of its |
| 561 | argument. It's easier in many cases in Go. Instead of "%llud" you |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 562 | can just say "%d"; "Printf" knows the size and signedness of the |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 563 | integer and can do the right thing for you. The snippet |
| 564 | |
| 565 | --PROG progs/print.go 'NR==6' 'NR==7' |
| 566 | |
| 567 | prints |
| 568 | |
| 569 | 18446744073709551615 -1 |
| 570 | |
| 571 | In fact, if you're lazy the format "%v" will print, in a simple |
| 572 | appropriate style, any value, even an array or structure. The output of |
| 573 | |
| 574 | --PROG progs/print.go 'NR==10' 'NR==13' |
| 575 | |
| 576 | is |
| 577 | |
| 578 | 18446744073709551615 {77 Sunset Strip} [1 2 3 4] |
| 579 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 580 | You can drop the formatting altogether if you use "Print" or "Println" |
| 581 | instead of "Printf". Those routines do fully automatic formatting. |
| 582 | The "Print" function just prints its elements out using the equivalent |
| 583 | of "%v" while "Println" automatically inserts spaces between arguments |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 584 | and adds a newline. The output of each of these two lines is identical |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 585 | to that of the "Printf" call above. |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 586 | |
| 587 | --PROG progs/print.go 'NR==14' 'NR==15' |
| 588 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 589 | If you have your own type you'd like "Printf" or "Print" to format, |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 590 | just give it a "String()" method that returns a string. The print |
| 591 | routines will examine the value to inquire whether it implements |
| 592 | the method and if so, use it rather than some other formatting. |
| 593 | Here's a simple example. |
| 594 | |
| 595 | --PROG progs/print_string.go 'NR==5' END |
| 596 | |
| 597 | Since "*T" has a "String()" method, the |
| 598 | default formatter for that type will use it and produce the output |
| 599 | |
| 600 | 77 Sunset Strip |
| 601 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 602 | Observe that the "String()" method calls "Sprint" (the obvious Go |
| 603 | variant that returns a string) to do its formatting; special formatters |
| 604 | can use the "fmt" library recursively. |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 605 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 606 | Another feature of "Printf" is that the format "%T" will print a string |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 607 | representation of the type of a value, which can be handy when debugging |
| 608 | polymorphic code. |
| 609 | |
| 610 | It's possible to write full custom print formats with flags and precisions |
| 611 | and such, but that's getting a little off the main thread so we'll leave it |
| 612 | as an exploration exercise. |
| 613 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 614 | You might ask, though, how "Printf" can tell whether a type implements |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 615 | the "String()" method. Actually what it does is ask if the value can |
| 616 | be converted to an interface variable that implements the method. |
| 617 | Schematically, given a value "v", it does this: |
| 618 | |
| 619 | |
| 620 | type String interface { |
| 621 | String() string |
| 622 | } |
| 623 | |
| 624 | s, ok := v.(String); // Test whether v satisfies "String" |
| 625 | if ok { |
| 626 | result = s.String() |
| 627 | } else { |
| 628 | result = default_output(v) |
| 629 | } |
| 630 | |
| 631 | The code tests if the value stored in |
| 632 | "v" satisfies the "String" interface; if it does, "s" |
| 633 | will become an interface variable implementing the method and "ok" will |
| 634 | be "true". We then use the interface variable to call the method. |
| 635 | (The ''comma, ok'' pattern is a Go idiom used to test the success of |
| 636 | operations such as type conversion, map update, communications, and so on, |
| 637 | although this is the only appearance in this tutorial.) |
| 638 | If the value does not satisfy the interface, "ok" will be false. |
| 639 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 640 | One last wrinkle. To complete the suite, besides "Printf" etc. and "Sprintf" |
| 641 | etc., there are also "Fprintf" etc. Unlike in C, "Fprintf"'s first argument is |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 642 | not a file. Instead, it is a variable of type "io.Write", which is an |
| 643 | interface type defined in the "io" library: |
| 644 | |
| 645 | export type Write interface { |
| 646 | Write(p []byte) (n int, err *os.Error); |
| 647 | } |
| 648 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 649 | Thus you can call "Fprintf" on any type that implements a standard "Write()" |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 650 | method, not just files but also network channels, buffers, rot13ers, whatever |
| 651 | you want. |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 652 | |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 653 | Prime numbers |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 654 | ---- |
| 655 | |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 656 | Now we come to processes and communication -- concurrent programming. |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 657 | It's a big subject so to be brief we assume some familiarity with the topic. |
| 658 | |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 659 | A classic program in the style is the prime sieve of Eratosthenes. |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 660 | It works by taking a stream of all the natural numbers and introducing |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 661 | a sequence of filters, one for each prime, to winnow the multiples of |
| 662 | that prime. At each step we have a sequence of filters of the primes |
| 663 | so far, and the next number to pop out is the next prime, which triggers |
| 664 | the creation of the next filter in the chain. |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 665 | |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 666 | Here's a flow diagram; each box represents a filter element whose |
| 667 | creation is triggered by the first number that flowed from the |
| 668 | elements before it. |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 669 | |
| 670 | <br> |
| 671 | |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 672 | <img src='sieve.gif'> |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 673 | |
| 674 | <br> |
| 675 | |
| 676 | To create a stream of integers, we use a Go <i>channel</i>, which, |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 677 | borrowing from CSP's descendants, represents a communications |
| 678 | channel that can connect two concurrent computations. |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 679 | In Go, channel variables are references to a run-time object that |
| 680 | coordinates the communication; as with maps and slices, use |
| 681 | "make" to create a new channel. |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 682 | |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 683 | Here is the first function in "progs/sieve.go": |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 684 | |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 685 | --PROG progs/sieve.go /Send/ /^}/ |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 686 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 687 | The "generate" function sends the sequence 2, 3, 4, 5, ... to its |
Ian Lance Taylor | 128f052 | 2008-09-22 11:29:40 -0700 | [diff] [blame] | 688 | argument channel, "ch", using the binary communications operator "<-". |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 689 | Channels block, so if there's no recipient for the the value on "ch", |
| 690 | the send operation will wait until one becomes available. |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 691 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 692 | The "filter" function has three arguments: an input channel, an output |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 693 | channel, and a prime number. It copies values from the input to the |
Rob Pike | 592d2e3 | 2008-09-16 19:40:38 -0700 | [diff] [blame] | 694 | output, discarding anything divisible by the prime. The unary communications |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 695 | operator "<-" (receive) retrieves the next value on the channel. |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 696 | |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 697 | --PROG progs/sieve.go /Copy/ /^}/ |
| 698 | |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 699 | The generator and filters execute concurrently. Go has |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 700 | its own model of process/threads/light-weight processes/coroutines, |
| 701 | so to avoid notational confusion we'll call concurrently executing |
| 702 | computations in Go <i>goroutines</i>. To start a goroutine, |
| 703 | invoke the function, prefixing the call with the keyword "go"; |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 704 | this starts the function running in parallel with the current |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 705 | computation but in the same address space: |
| 706 | |
| 707 | go sum(huge_array); // calculate sum in the background |
| 708 | |
| 709 | If you want to know when the calculation is done, pass a channel |
| 710 | on which it can report back: |
| 711 | |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 712 | ch := make(chan int); |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 713 | go sum(huge_array, ch); |
| 714 | // ... do something else for a while |
| 715 | result := <-ch; // wait for, and retrieve, result |
| 716 | |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 717 | Back to our prime sieve. Here's how the sieve pipeline is stitched |
| 718 | together: |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 719 | |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 720 | --PROG progs/sieve.go /func.main/ /^}/ |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 721 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 722 | Line 23 creates the initial channel to pass to "generate", which it |
| 723 | then starts up. As each prime pops out of the channel, a new "filter" |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 724 | is added to the pipeline and <i>its</i> output becomes the new value |
| 725 | of "ch". |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 726 | |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 727 | The sieve program can be tweaked to use a pattern common |
| 728 | in this style of programming. Here is a variant version |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 729 | of "generate", from "progs/sieve1.go": |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 730 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 731 | --PROG progs/sieve1.go /func.generate/ /^}/ |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 732 | |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 733 | This version does all the setup internally. It creates the output |
| 734 | channel, launches a goroutine internally using a function literal, and |
| 735 | returns the channel to the caller. It is a factory for concurrent |
| 736 | execution, starting the goroutine and returning its connection. |
| 737 | The same |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 738 | change can be made to "filter": |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 739 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 740 | --PROG progs/sieve1.go /func.filter/ /^}/ |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 741 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 742 | The "sieve" function's main loop becomes simpler and clearer as a |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 743 | result, and while we're at it let's turn it into a factory too: |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 744 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 745 | --PROG progs/sieve1.go /func.sieve/ /^}/ |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 746 | |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 747 | Now "main"'s interface to the prime sieve is a channel of primes: |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 748 | |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 749 | --PROG progs/sieve1.go /func.main/ /^}/ |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 750 | |
Rob Pike | 6820196 | 2008-09-16 13:14:44 -0700 | [diff] [blame] | 751 | Multiplexing |
Rob Pike | db9002f | 2008-09-16 11:00:11 -0700 | [diff] [blame] | 752 | ---- |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 753 | |
Rob Pike | 6820196 | 2008-09-16 13:14:44 -0700 | [diff] [blame] | 754 | With channels, it's possible to serve multiple independent client goroutines without |
| 755 | writing an actual multiplexer. The trick is to send the server a channel in the message, |
| 756 | which it will then use to reply to the original sender. |
| 757 | A realistic client-server program is a lot of code, so here is a very simple substitute |
Rob Pike | 81672ef | 2008-09-29 20:06:48 -0700 | [diff] [blame] | 758 | to illustrate the idea. It starts by defining a "Request" type, which embeds a channel |
Rob Pike | 6820196 | 2008-09-16 13:14:44 -0700 | [diff] [blame] | 759 | that will be used for the reply. |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 760 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 761 | --PROG progs/server.go /type.request/ /^}/ |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 762 | |
Rob Pike | 6820196 | 2008-09-16 13:14:44 -0700 | [diff] [blame] | 763 | The server will be trivial: it will do simple binary operations on integers. Here's the |
| 764 | code that invokes the operation and responds to the request: |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 765 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 766 | --PROG progs/server.go /type.binOp/ /^}/ |
Rob Pike | a43033a | 2008-09-15 11:48:37 -0700 | [diff] [blame] | 767 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 768 | Line 8 defines the name "binOp" to be a function taking two integers and |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 769 | returning a third. |
| 770 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 771 | The "server" routine loops forever, receiving requests and, to avoid blocking due to |
Rob Pike | 6820196 | 2008-09-16 13:14:44 -0700 | [diff] [blame] | 772 | a long-running operation, starting a goroutine to do the actual work. |
| 773 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 774 | --PROG progs/server.go /func.server/ /^}/ |
Rob Pike | 6820196 | 2008-09-16 13:14:44 -0700 | [diff] [blame] | 775 | |
| 776 | We construct a server in a familiar way, starting it up and returning a channel to |
| 777 | connect to it: |
| 778 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 779 | --PROG progs/server.go /func.startServer/ /^}/ |
Rob Pike | 6820196 | 2008-09-16 13:14:44 -0700 | [diff] [blame] | 780 | |
| 781 | Here's a simple test. It starts a server with an addition operator, and sends out |
| 782 | lots of requests but doesn't wait for the reply. Only after all the requests are sent |
| 783 | does it check the results. |
| 784 | |
| 785 | --PROG progs/server.go /func.main/ /^}/ |
| 786 | |
| 787 | One annoyance with this program is that it doesn't exit cleanly; when "main" returns |
| 788 | there are a number of lingering goroutines blocked on communication. To solve this, |
Rob Pike | 40d5435 | 2009-01-09 15:16:31 -0800 | [diff] [blame] | 789 | we can provide a second, "quit" channel to the server: |
Rob Pike | 6820196 | 2008-09-16 13:14:44 -0700 | [diff] [blame] | 790 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 791 | --PROG progs/server1.go /func.startServer/ /^}/ |
Rob Pike | 6820196 | 2008-09-16 13:14:44 -0700 | [diff] [blame] | 792 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 793 | It passes the quit channel to the "server" function, which uses it like this: |
Rob Pike | 6820196 | 2008-09-16 13:14:44 -0700 | [diff] [blame] | 794 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 795 | --PROG progs/server1.go /func.server/ /^}/ |
Rob Pike | 6820196 | 2008-09-16 13:14:44 -0700 | [diff] [blame] | 796 | |
Rob Pike | ae05f00 | 2009-01-20 19:32:36 -0800 | [diff] [blame] | 797 | Inside "server", a "select" statement chooses which of the multiple communications |
Rob Pike | 6820196 | 2008-09-16 13:14:44 -0700 | [diff] [blame] | 798 | listed by its cases can proceed. If all are blocked, it waits until one can proceed; if |
| 799 | multiple can proceed, it chooses one at random. In this instance, the "select" allows |
| 800 | the server to honor requests until it receives a quit message, at which point it |
Rob Pike | 592d2e3 | 2008-09-16 19:40:38 -0700 | [diff] [blame] | 801 | returns, terminating its execution. |
Rob Pike | 6820196 | 2008-09-16 13:14:44 -0700 | [diff] [blame] | 802 | |
| 803 | |
| 804 | All that's left is to strobe the "quit" channel |
| 805 | at the end of main: |
| 806 | |
| 807 | --PROG progs/server1.go /adder,.quit/ |
| 808 | ... |
| 809 | --PROG progs/server1.go /quit....true/ |
| 810 | |
| 811 | There's a lot more to Go programming and concurrent programming in general but this |
| 812 | quick tour should give you some of the basics. |