github.com/spotify/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/doc/effective_go.html (about) 1 <!--{ 2 "Title": "Effective Go", 3 "Template": true 4 }--> 5 6 <h2 id="introduction">Introduction</h2> 7 8 <p> 9 Go is a new language. Although it borrows ideas from 10 existing languages, 11 it has unusual properties that make effective Go programs 12 different in character from programs written in its relatives. 13 A straightforward translation of a C++ or Java program into Go 14 is unlikely to produce a satisfactory result—Java programs 15 are written in Java, not Go. 16 On the other hand, thinking about the problem from a Go 17 perspective could produce a successful but quite different 18 program. 19 In other words, 20 to write Go well, it's important to understand its properties 21 and idioms. 22 It's also important to know the established conventions for 23 programming in Go, such as naming, formatting, program 24 construction, and so on, so that programs you write 25 will be easy for other Go programmers to understand. 26 </p> 27 28 <p> 29 This document gives tips for writing clear, idiomatic Go code. 30 It augments the <a href="/ref/spec">language specification</a>, 31 the <a href="http://tour.golang.org/">Tour of Go</a>, 32 and <a href="/doc/code.html">How to Write Go Code</a>, 33 all of which you 34 should read first. 35 </p> 36 37 <h3 id="examples">Examples</h3> 38 39 <p> 40 The <a href="/src/pkg/">Go package sources</a> 41 are intended to serve not 42 only as the core library but also as examples of how to 43 use the language. 44 Moreover, many of the packages contain working, self-contained 45 executable examples you can run directly from the 46 <a href="http://golang.org">golang.org</a> web site, such as 47 <a href="http://golang.org/pkg/strings/#example_Map">this one</a> (if 48 necessary, click on the word "Example" to open it up). 49 If you have a question about how to approach a problem or how something 50 might be implemented, the documentation, code and examples in the 51 library can provide answers, ideas and 52 background. 53 </p> 54 55 56 <h2 id="formatting">Formatting</h2> 57 58 <p> 59 Formatting issues are the most contentious 60 but the least consequential. 61 People can adapt to different formatting styles 62 but it's better if they don't have to, and 63 less time is devoted to the topic 64 if everyone adheres to the same style. 65 The problem is how to approach this Utopia without a long 66 prescriptive style guide. 67 </p> 68 69 <p> 70 With Go we take an unusual 71 approach and let the machine 72 take care of most formatting issues. 73 The <code>gofmt</code> program 74 (also available as <code>go fmt</code>, which 75 operates at the package level rather than source file level) 76 reads a Go program 77 and emits the source in a standard style of indentation 78 and vertical alignment, retaining and if necessary 79 reformatting comments. 80 If you want to know how to handle some new layout 81 situation, run <code>gofmt</code>; if the answer doesn't 82 seem right, rearrange your program (or file a bug about <code>gofmt</code>), 83 don't work around it. 84 </p> 85 86 <p> 87 As an example, there's no need to spend time lining up 88 the comments on the fields of a structure. 89 <code>Gofmt</code> will do that for you. Given the 90 declaration 91 </p> 92 93 <pre> 94 type T struct { 95 name string // name of the object 96 value int // its value 97 } 98 </pre> 99 100 <p> 101 <code>gofmt</code> will line up the columns: 102 </p> 103 104 <pre> 105 type T struct { 106 name string // name of the object 107 value int // its value 108 } 109 </pre> 110 111 <p> 112 All Go code in the standard packages has been formatted with <code>gofmt</code>. 113 </p> 114 115 116 <p> 117 Some formatting details remain. Very briefly: 118 </p> 119 120 <dl> 121 <dt>Indentation</dt> 122 <dd>We use tabs for indentation and <code>gofmt</code> emits them by default. 123 Use spaces only if you must. 124 </dd> 125 <dt>Line length</dt> 126 <dd> 127 Go has no line length limit. Don't worry about overflowing a punched card. 128 If a line feels too long, wrap it and indent with an extra tab. 129 </dd> 130 <dt>Parentheses</dt> 131 <dd> 132 Go needs fewer parentheses than C and Java: control structures (<code>if</code>, 133 <code>for</code>, <code>switch</code>) do not have parentheses in 134 their syntax. 135 Also, the operator precedence hierarchy is shorter and clearer, so 136 <pre> 137 x<<8 + y<<16 138 </pre> 139 means what the spacing implies, unlike in the other languages. 140 </dd> 141 </dl> 142 143 <h2 id="commentary">Commentary</h2> 144 145 <p> 146 Go provides C-style <code>/* */</code> block comments 147 and C++-style <code>//</code> line comments. 148 Line comments are the norm; 149 block comments appear mostly as package comments, but 150 are useful within an expression or to disable large swaths of code. 151 </p> 152 153 <p> 154 The program—and web server—<code>godoc</code> processes 155 Go source files to extract documentation about the contents of the 156 package. 157 Comments that appear before top-level declarations, with no intervening newlines, 158 are extracted along with the declaration to serve as explanatory text for the item. 159 The nature and style of these comments determines the 160 quality of the documentation <code>godoc</code> produces. 161 </p> 162 163 <p> 164 Every package should have a <i>package comment</i>, a block 165 comment preceding the package clause. 166 For multi-file packages, the package comment only needs to be 167 present in one file, and any one will do. 168 The package comment should introduce the package and 169 provide information relevant to the package as a whole. 170 It will appear first on the <code>godoc</code> page and 171 should set up the detailed documentation that follows. 172 </p> 173 174 <pre> 175 /* 176 Package regexp implements a simple library for regular expressions. 177 178 The syntax of the regular expressions accepted is: 179 180 regexp: 181 concatenation { '|' concatenation } 182 concatenation: 183 { closure } 184 closure: 185 term [ '*' | '+' | '?' ] 186 term: 187 '^' 188 '$' 189 '.' 190 character 191 '[' [ '^' ] character-ranges ']' 192 '(' regexp ')' 193 */ 194 package regexp 195 </pre> 196 197 <p> 198 If the package is simple, the package comment can be brief. 199 </p> 200 201 <pre> 202 // Package path implements utility routines for 203 // manipulating slash-separated filename paths. 204 </pre> 205 206 <p> 207 Comments do not need extra formatting such as banners of stars. 208 The generated output may not even be presented in a fixed-width font, so don't depend 209 on spacing for alignment—<code>godoc</code>, like <code>gofmt</code>, 210 takes care of that. 211 The comments are uninterpreted plain text, so HTML and other 212 annotations such as <code>_this_</code> will reproduce <i>verbatim</i> and should 213 not be used. 214 One adjustment <code>godoc</code> does do is to display indented 215 text in a fixed-width font, suitable for program snippets. 216 The package comment for the 217 <a href="http://golang.org/pkg/fmt/"><code>fmt</code> package</a> uses this to good effect. 218 </p> 219 220 <p> 221 Depending on the context, <code>godoc</code> might not even 222 reformat comments, so make sure they look good straight up: 223 use correct spelling, punctuation, and sentence structure, 224 fold long lines, and so on. 225 </p> 226 227 <p> 228 Inside a package, any comment immediately preceding a top-level declaration 229 serves as a <i>doc comment</i> for that declaration. 230 Every exported (capitalized) name in a program should 231 have a doc comment. 232 </p> 233 234 <p> 235 Doc comments work best as complete sentences, which allow 236 a wide variety of automated presentations. 237 The first sentence should be a one-sentence summary that 238 starts with the name being declared. 239 </p> 240 241 <pre> 242 // Compile parses a regular expression and returns, if successful, a Regexp 243 // object that can be used to match against text. 244 func Compile(str string) (regexp *Regexp, err error) { 245 </pre> 246 247 <p> 248 If the name always begins the comment, the output of <code>godoc</code> 249 can usefully be run through <code>grep</code>. 250 Imagine you couldn't remember the name "Compile" but were looking for 251 the parsing function for regular expressions, so you ran 252 the command, 253 </p> 254 255 <pre> 256 $ godoc regexp | grep parse 257 </pre> 258 259 <p> 260 If all the doc comments in the package began, "This function...", <code>grep</code> 261 wouldn't help you remember the name. But because the package starts each 262 doc comment with the name, you'd see something like this, 263 which recalls the word you're looking for. 264 </p> 265 266 <pre> 267 $ godoc regexp | grep parse 268 Compile parses a regular expression and returns, if successful, a Regexp 269 parsed. It simplifies safe initialization of global variables holding 270 cannot be parsed. It simplifies safe initialization of global variables 271 $ 272 </pre> 273 274 <p> 275 Go's declaration syntax allows grouping of declarations. 276 A single doc comment can introduce a group of related constants or variables. 277 Since the whole declaration is presented, such a comment can often be perfunctory. 278 </p> 279 280 <pre> 281 // Error codes returned by failures to parse an expression. 282 var ( 283 ErrInternal = errors.New("regexp: internal error") 284 ErrUnmatchedLpar = errors.New("regexp: unmatched '('") 285 ErrUnmatchedRpar = errors.New("regexp: unmatched ')'") 286 ... 287 ) 288 </pre> 289 290 <p> 291 Even for private names, grouping can also indicate relationships between items, 292 such as the fact that a set of variables is protected by a mutex. 293 </p> 294 295 <pre> 296 var ( 297 countLock sync.Mutex 298 inputCount uint32 299 outputCount uint32 300 errorCount uint32 301 ) 302 </pre> 303 304 <h2 id="names">Names</h2> 305 306 <p> 307 Names are as important in Go as in any other language. 308 They even have semantic effect: 309 the visibility of a name outside a package is determined by whether its 310 first character is upper case. 311 It's therefore worth spending a little time talking about naming conventions 312 in Go programs. 313 </p> 314 315 316 <h3 id="package-names">Package names</h3> 317 318 <p> 319 When a package is imported, the package name becomes an accessor for the 320 contents. After 321 </p> 322 323 <pre> 324 import "bytes" 325 </pre> 326 327 <p> 328 the importing package can talk about <code>bytes.Buffer</code>. It's 329 helpful if everyone using the package can use the same name to refer to 330 its contents, which implies that the package name should be good: 331 short, concise, evocative. By convention, packages are given 332 lower case, single-word names; there should be no need for underscores 333 or mixedCaps. 334 Err on the side of brevity, since everyone using your 335 package will be typing that name. 336 And don't worry about collisions <i>a priori</i>. 337 The package name is only the default name for imports; it need not be unique 338 across all source code, and in the rare case of a collision the 339 importing package can choose a different name to use locally. 340 In any case, confusion is rare because the file name in the import 341 determines just which package is being used. 342 </p> 343 344 <p> 345 Another convention is that the package name is the base name of 346 its source directory; 347 the package in <code>src/pkg/encoding/base64</code> 348 is imported as <code>"encoding/base64"</code> but has name <code>base64</code>, 349 not <code>encoding_base64</code> and not <code>encodingBase64</code>. 350 </p> 351 352 <p> 353 The importer of a package will use the name to refer to its contents. 354 so exported names in the package can use that fact 355 to avoid stutter. 356 (Don't use the <code>import .</code> notation, which can simplify 357 tests that must run outside the package they are testing, but should otherwise be avoided.) 358 For instance, the buffered reader type in the <code>bufio</code> package is called <code>Reader</code>, 359 not <code>BufReader</code>, because users see it as <code>bufio.Reader</code>, 360 which is a clear, concise name. 361 Moreover, 362 because imported entities are always addressed with their package name, <code>bufio.Reader</code> 363 does not conflict with <code>io.Reader</code>. 364 Similarly, the function to make new instances of <code>ring.Ring</code>—which 365 is the definition of a <em>constructor</em> in Go—would 366 normally be called <code>NewRing</code>, but since 367 <code>Ring</code> is the only type exported by the package, and since the 368 package is called <code>ring</code>, it's called just <code>New</code>, 369 which clients of the package see as <code>ring.New</code>. 370 Use the package structure to help you choose good names. 371 </p> 372 373 <p> 374 Another short example is <code>once.Do</code>; 375 <code>once.Do(setup)</code> reads well and would not be improved by 376 writing <code>once.DoOrWaitUntilDone(setup)</code>. 377 Long names don't automatically make things more readable. 378 A helpful doc comment can often be more valuable than an extra long name. 379 </p> 380 381 <h3 id="Getters">Getters</h3> 382 383 <p> 384 Go doesn't provide automatic support for getters and setters. 385 There's nothing wrong with providing getters and setters yourself, 386 and it's often appropriate to do so, but it's neither idiomatic nor necessary 387 to put <code>Get</code> into the getter's name. If you have a field called 388 <code>owner</code> (lower case, unexported), the getter method should be 389 called <code>Owner</code> (upper case, exported), not <code>GetOwner</code>. 390 The use of upper-case names for export provides the hook to discriminate 391 the field from the method. 392 A setter function, if needed, will likely be called <code>SetOwner</code>. 393 Both names read well in practice: 394 </p> 395 <pre> 396 owner := obj.Owner() 397 if owner != user { 398 obj.SetOwner(user) 399 } 400 </pre> 401 402 <h3 id="interface-names">Interface names</h3> 403 404 <p> 405 By convention, one-method interfaces are named by 406 the method name plus an -er suffix or similar modification 407 to construct an agent noun: <code>Reader</code>, 408 <code>Writer</code>, <code>Formatter</code>, 409 <code>CloseNotifier</code> etc. 410 </p> 411 412 <p> 413 There are a number of such names and it's productive to honor them and the function 414 names they capture. 415 <code>Read</code>, <code>Write</code>, <code>Close</code>, <code>Flush</code>, 416 <code>String</code> and so on have 417 canonical signatures and meanings. To avoid confusion, 418 don't give your method one of those names unless it 419 has the same signature and meaning. 420 Conversely, if your type implements a method with the 421 same meaning as a method on a well-known type, 422 give it the same name and signature; 423 call your string-converter method <code>String</code> not <code>ToString</code>. 424 </p> 425 426 <h3 id="mixed-caps">MixedCaps</h3> 427 428 <p> 429 Finally, the convention in Go is to use <code>MixedCaps</code> 430 or <code>mixedCaps</code> rather than underscores to write 431 multiword names. 432 </p> 433 434 <h2 id="semicolons">Semicolons</h2> 435 436 <p> 437 Like C, Go's formal grammar uses semicolons to terminate statements, 438 but unlike in C, those semicolons do not appear in the source. 439 Instead the lexer uses a simple rule to insert semicolons automatically 440 as it scans, so the input text is mostly free of them. 441 </p> 442 443 <p> 444 The rule is this. If the last token before a newline is an identifier 445 (which includes words like <code>int</code> and <code>float64</code>), 446 a basic literal such as a number or string constant, or one of the 447 tokens 448 </p> 449 <pre> 450 break continue fallthrough return ++ -- ) } 451 </pre> 452 <p> 453 the lexer always inserts a semicolon after the token. 454 This could be summarized as, “if the newline comes 455 after a token that could end a statement, insert a semicolon”. 456 </p> 457 458 <p> 459 A semicolon can also be omitted immediately before a closing brace, 460 so a statement such as 461 </p> 462 <pre> 463 go func() { for { dst <- <-src } }() 464 </pre> 465 <p> 466 needs no semicolons. 467 Idiomatic Go programs have semicolons only in places such as 468 <code>for</code> loop clauses, to separate the initializer, condition, and 469 continuation elements. They are also necessary to separate multiple 470 statements on a line, should you write code that way. 471 </p> 472 473 <p> 474 One consequence of the semicolon insertion rules 475 is that you cannot put the opening brace of a 476 control structure (<code>if</code>, <code>for</code>, <code>switch</code>, 477 or <code>select</code>) on the next line. If you do, a semicolon 478 will be inserted before the brace, which could cause unwanted 479 effects. Write them like this 480 </p> 481 482 <pre> 483 if i < f() { 484 g() 485 } 486 </pre> 487 <p> 488 not like this 489 </p> 490 <pre> 491 if i < f() // wrong! 492 { // wrong! 493 g() 494 } 495 </pre> 496 497 498 <h2 id="control-structures">Control structures</h2> 499 500 <p> 501 The control structures of Go are related to those of C but differ 502 in important ways. 503 There is no <code>do</code> or <code>while</code> loop, only a 504 slightly generalized 505 <code>for</code>; 506 <code>switch</code> is more flexible; 507 <code>if</code> and <code>switch</code> accept an optional 508 initialization statement like that of <code>for</code>; 509 <code>break</code> and <code>continue</code> statements 510 take an optional label to identify what to break or continue; 511 and there are new control structures including a type switch and a 512 multiway communications multiplexer, <code>select</code>. 513 The syntax is also slightly different: 514 there are no parentheses 515 and the bodies must always be brace-delimited. 516 </p> 517 518 <h3 id="if">If</h3> 519 520 <p> 521 In Go a simple <code>if</code> looks like this: 522 </p> 523 <pre> 524 if x > 0 { 525 return y 526 } 527 </pre> 528 529 <p> 530 Mandatory braces encourage writing simple <code>if</code> statements 531 on multiple lines. It's good style to do so anyway, 532 especially when the body contains a control statement such as a 533 <code>return</code> or <code>break</code>. 534 </p> 535 536 <p> 537 Since <code>if</code> and <code>switch</code> accept an initialization 538 statement, it's common to see one used to set up a local variable. 539 </p> 540 541 <pre> 542 if err := file.Chmod(0664); err != nil { 543 log.Print(err) 544 return err 545 } 546 </pre> 547 548 <p id="else"> 549 In the Go libraries, you'll find that 550 when an <code>if</code> statement doesn't flow into the next statement—that is, 551 the body ends in <code>break</code>, <code>continue</code>, 552 <code>goto</code>, or <code>return</code>—the unnecessary 553 <code>else</code> is omitted. 554 </p> 555 556 <pre> 557 f, err := os.Open(name) 558 if err != nil { 559 return err 560 } 561 codeUsing(f) 562 </pre> 563 564 <p> 565 This is an example of a common situation where code must guard against a 566 sequence of error conditions. The code reads well if the 567 successful flow of control runs down the page, eliminating error cases 568 as they arise. Since error cases tend to end in <code>return</code> 569 statements, the resulting code needs no <code>else</code> statements. 570 </p> 571 572 <pre> 573 f, err := os.Open(name) 574 if err != nil { 575 return err 576 } 577 d, err := f.Stat() 578 if err != nil { 579 f.Close() 580 return err 581 } 582 codeUsing(f, d) 583 </pre> 584 585 586 <h3 id="redeclaration">Redeclaration and reassignment</h3> 587 588 <p> 589 An aside: The last example in the previous section demonstrates a detail of how the 590 <code>:=</code> short declaration form works. 591 The declaration that calls <code>os.Open</code> reads, 592 </p> 593 594 <pre> 595 f, err := os.Open(name) 596 </pre> 597 598 <p> 599 This statement declares two variables, <code>f</code> and <code>err</code>. 600 A few lines later, the call to <code>f.Stat</code> reads, 601 </p> 602 603 <pre> 604 d, err := f.Stat() 605 </pre> 606 607 <p> 608 which looks as if it declares <code>d</code> and <code>err</code>. 609 Notice, though, that <code>err</code> appears in both statements. 610 This duplication is legal: <code>err</code> is declared by the first statement, 611 but only <em>re-assigned</em> in the second. 612 This means that the call to <code>f.Stat</code> uses the existing 613 <code>err</code> variable declared above, and just gives it a new value. 614 </p> 615 616 <p> 617 In a <code>:=</code> declaration a variable <code>v</code> may appear even 618 if it has already been declared, provided: 619 </p> 620 621 <ul> 622 <li>this declaration is in the same scope as the existing declaration of <code>v</code> 623 (if <code>v</code> is already declared in an outer scope, the declaration will create a new variable §),</li> 624 <li>the corresponding value in the initialization is assignable to <code>v</code>, and</li> 625 <li>there is at least one other variable in the declaration that is being declared anew.</li> 626 </ul> 627 628 <p> 629 This unusual property is pure pragmatism, 630 making it easy to use a single <code>err</code> value, for example, 631 in a long <code>if-else</code> chain. 632 You'll see it used often. 633 </p> 634 635 <p> 636 § It's worth noting here that in Go the scope of function parameters and return values 637 is the same as the function body, even though they appear lexically outside the braces 638 that enclose the body. 639 </p> 640 641 <h3 id="for">For</h3> 642 643 <p> 644 The Go <code>for</code> loop is similar to—but not the same as—C's. 645 It unifies <code>for</code> 646 and <code>while</code> and there is no <code>do-while</code>. 647 There are three forms, only one of which has semicolons. 648 </p> 649 <pre> 650 // Like a C for 651 for init; condition; post { } 652 653 // Like a C while 654 for condition { } 655 656 // Like a C for(;;) 657 for { } 658 </pre> 659 660 <p> 661 Short declarations make it easy to declare the index variable right in the loop. 662 </p> 663 <pre> 664 sum := 0 665 for i := 0; i < 10; i++ { 666 sum += i 667 } 668 </pre> 669 670 <p> 671 If you're looping over an array, slice, string, or map, 672 or reading from a channel, a <code>range</code> clause can 673 manage the loop. 674 </p> 675 <pre> 676 for key, value := range oldMap { 677 newMap[key] = value 678 } 679 </pre> 680 681 <p> 682 If you only need the first item in the range (the key or index), drop the second: 683 </p> 684 <pre> 685 for key := range m { 686 if key.expired() { 687 delete(m, key) 688 } 689 } 690 </pre> 691 692 <p> 693 If you only need the second item in the range (the value), use the <em>blank identifier</em>, an underscore, to discard the first: 694 </p> 695 <pre> 696 sum := 0 697 for _, value := range array { 698 sum += value 699 } 700 </pre> 701 702 <p> 703 The blank identifier has many uses, as described in <a href="#blank">a later section</a>. 704 705 <p> 706 For strings, the <code>range</code> does more work for you, breaking out individual 707 Unicode code points by parsing the UTF-8. 708 Erroneous encodings consume one byte and produce the 709 replacement rune U+FFFD. 710 (The name (with associated builtin type) <code>rune</code> is Go terminology for a 711 single Unicode code point. 712 See <a href="http://golang.org/ref/spec#Rune_literals">the language specification</a> 713 for details.) 714 The loop 715 </p> 716 <pre> 717 for pos, char := range "日本\x80語" { // \x80 is an illegal UTF-8 encoding 718 fmt.Printf("character %#U starts at byte position %d\n", char, pos) 719 } 720 </pre> 721 <p> 722 prints 723 </p> 724 <pre> 725 character U+65E5 '日' starts at byte position 0 726 character U+672C '本' starts at byte position 3 727 character U+FFFD '�' starts at byte position 6 728 character U+8A9E '語' starts at byte position 7 729 </pre> 730 731 <p> 732 Finally, Go has no comma operator and <code>++</code> and <code>--</code> 733 are statements not expressions. 734 Thus if you want to run multiple variables in a <code>for</code> 735 you should use parallel assignment (although that precludes <code>++</code> and <code>--</code>). 736 </p> 737 <pre> 738 // Reverse a 739 for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 { 740 a[i], a[j] = a[j], a[i] 741 } 742 </pre> 743 744 <h3 id="switch">Switch</h3> 745 746 <p> 747 Go's <code>switch</code> is more general than C's. 748 The expressions need not be constants or even integers, 749 the cases are evaluated top to bottom until a match is found, 750 and if the <code>switch</code> has no expression it switches on 751 <code>true</code>. 752 It's therefore possible—and idiomatic—to write an 753 <code>if</code>-<code>else</code>-<code>if</code>-<code>else</code> 754 chain as a <code>switch</code>. 755 </p> 756 757 <pre> 758 func unhex(c byte) byte { 759 switch { 760 case '0' <= c && c <= '9': 761 return c - '0' 762 case 'a' <= c && c <= 'f': 763 return c - 'a' + 10 764 case 'A' <= c && c <= 'F': 765 return c - 'A' + 10 766 } 767 return 0 768 } 769 </pre> 770 771 <p> 772 There is no automatic fall through, but cases can be presented 773 in comma-separated lists. 774 </p> 775 <pre> 776 func shouldEscape(c byte) bool { 777 switch c { 778 case ' ', '?', '&', '=', '#', '+', '%': 779 return true 780 } 781 return false 782 } 783 </pre> 784 785 <p> 786 Although they are not nearly as common in Go as some other C-like 787 languages, <code>break</code> statements can be used to terminate 788 a <code>switch</code> early. 789 Sometimes, though, it's necessary to break out of a surrounding loop, 790 not the switch, and in Go that can be accomplished by putting a label 791 on the loop and "breaking" to that label. 792 This example shows both uses. 793 </p> 794 795 <pre> 796 Loop: 797 for n := 0; n < len(src); n += size { 798 switch { 799 case src[n] < sizeOne: 800 if validateOnly { 801 break 802 } 803 size = 1 804 update(src[n]) 805 806 case src[n] < sizeTwo: 807 if n+1 >= len(src) { 808 err = errShortInput 809 break Loop 810 } 811 if validateOnly { 812 break 813 } 814 size = 2 815 update(src[n] + src[n+1]<<shift) 816 } 817 } 818 </pre> 819 820 <p> 821 Of course, the <code>continue</code> statement also accepts an optional label 822 but it applies only to loops. 823 </p> 824 825 <p> 826 To close this section, here's a comparison routine for byte slices that uses two 827 <code>switch</code> statements: 828 </p> 829 <pre> 830 // Compare returns an integer comparing the two byte slices, 831 // lexicographically. 832 // The result will be 0 if a == b, -1 if a < b, and +1 if a > b 833 func Compare(a, b []byte) int { 834 for i := 0; i < len(a) && i < len(b); i++ { 835 switch { 836 case a[i] > b[i]: 837 return 1 838 case a[i] < b[i]: 839 return -1 840 } 841 } 842 switch { 843 case len(a) > len(b): 844 return 1 845 case len(a) < len(b): 846 return -1 847 } 848 return 0 849 } 850 </pre> 851 852 <h2 id="type_switch">Type switch</h2> 853 854 <p> 855 A switch can also be used to discover the dynamic type of an interface 856 variable. Such a <em>type switch</em> uses the syntax of a type 857 assertion with the keyword <code>type</code> inside the parentheses. 858 If the switch declares a variable in the expression, the variable will 859 have the corresponding type in each clause. 860 It's also idiomatic to reuse the name in such cases, in effect declaring 861 a new variable with the same name but a different type in each case. 862 </p> 863 <pre> 864 var t interface{} 865 t = functionOfSomeType() 866 switch t := t.(type) { 867 default: 868 fmt.Printf("unexpected type %T", t) // %T prints whatever type t has 869 case bool: 870 fmt.Printf("boolean %t\n", t) // t has type bool 871 case int: 872 fmt.Printf("integer %d\n", t) // t has type int 873 case *bool: 874 fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool 875 case *int: 876 fmt.Printf("pointer to integer %d\n", *t) // t has type *int 877 } 878 </pre> 879 880 <h2 id="functions">Functions</h2> 881 882 <h3 id="multiple-returns">Multiple return values</h3> 883 884 <p> 885 One of Go's unusual features is that functions and methods 886 can return multiple values. This form can be used to 887 improve on a couple of clumsy idioms in C programs: in-band 888 error returns such as <code>-1</code> for <code>EOF</code> 889 and modifying an argument passed by address. 890 </p> 891 892 <p> 893 In C, a write error is signaled by a negative count with the 894 error code secreted away in a volatile location. 895 In Go, <code>Write</code> 896 can return a count <i>and</i> an error: “Yes, you wrote some 897 bytes but not all of them because you filled the device”. 898 The signature of the <code>Write</code> method on files from 899 package <code>os</code> is: 900 </p> 901 902 <pre> 903 func (file *File) Write(b []byte) (n int, err error) 904 </pre> 905 906 <p> 907 and as the documentation says, it returns the number of bytes 908 written and a non-nil <code>error</code> when <code>n</code> 909 <code>!=</code> <code>len(b)</code>. 910 This is a common style; see the section on error handling for more examples. 911 </p> 912 913 <p> 914 A similar approach obviates the need to pass a pointer to a return 915 value to simulate a reference parameter. 916 Here's a simple-minded function to 917 grab a number from a position in a byte slice, returning the number 918 and the next position. 919 </p> 920 921 <pre> 922 func nextInt(b []byte, i int) (int, int) { 923 for ; i < len(b) && !isDigit(b[i]); i++ { 924 } 925 x := 0 926 for ; i < len(b) && isDigit(b[i]); i++ { 927 x = x*10 + int(b[i]) - '0' 928 } 929 return x, i 930 } 931 </pre> 932 933 <p> 934 You could use it to scan the numbers in an input slice <code>b</code> like this: 935 </p> 936 937 <pre> 938 for i := 0; i < len(b); { 939 x, i = nextInt(b, i) 940 fmt.Println(x) 941 } 942 </pre> 943 944 <h3 id="named-results">Named result parameters</h3> 945 946 <p> 947 The return or result "parameters" of a Go function can be given names and 948 used as regular variables, just like the incoming parameters. 949 When named, they are initialized to the zero values for their types when 950 the function begins; if the function executes a <code>return</code> statement 951 with no arguments, the current values of the result parameters are 952 used as the returned values. 953 </p> 954 955 <p> 956 The names are not mandatory but they can make code shorter and clearer: 957 they're documentation. 958 If we name the results of <code>nextInt</code> it becomes 959 obvious which returned <code>int</code> 960 is which. 961 </p> 962 963 <pre> 964 func nextInt(b []byte, pos int) (value, nextPos int) { 965 </pre> 966 967 <p> 968 Because named results are initialized and tied to an unadorned return, they can simplify 969 as well as clarify. Here's a version 970 of <code>io.ReadFull</code> that uses them well: 971 </p> 972 973 <pre> 974 func ReadFull(r Reader, buf []byte) (n int, err error) { 975 for len(buf) > 0 && err == nil { 976 var nr int 977 nr, err = r.Read(buf) 978 n += nr 979 buf = buf[nr:] 980 } 981 return 982 } 983 </pre> 984 985 <h3 id="defer">Defer</h3> 986 987 <p> 988 Go's <code>defer</code> statement schedules a function call (the 989 <i>deferred</i> function) to be run immediately before the function 990 executing the <code>defer</code> returns. It's an unusual but 991 effective way to deal with situations such as resources that must be 992 released regardless of which path a function takes to return. The 993 canonical examples are unlocking a mutex or closing a file. 994 </p> 995 996 <pre> 997 // Contents returns the file's contents as a string. 998 func Contents(filename string) (string, error) { 999 f, err := os.Open(filename) 1000 if err != nil { 1001 return "", err 1002 } 1003 defer f.Close() // f.Close will run when we're finished. 1004 1005 var result []byte 1006 buf := make([]byte, 100) 1007 for { 1008 n, err := f.Read(buf[0:]) 1009 result = append(result, buf[0:n]...) // append is discussed later. 1010 if err != nil { 1011 if err == io.EOF { 1012 break 1013 } 1014 return "", err // f will be closed if we return here. 1015 } 1016 } 1017 return string(result), nil // f will be closed if we return here. 1018 } 1019 </pre> 1020 1021 <p> 1022 Deferring a call to a function such as <code>Close</code> has two advantages. First, it 1023 guarantees that you will never forget to close the file, a mistake 1024 that's easy to make if you later edit the function to add a new return 1025 path. Second, it means that the close sits near the open, 1026 which is much clearer than placing it at the end of the function. 1027 </p> 1028 1029 <p> 1030 The arguments to the deferred function (which include the receiver if 1031 the function is a method) are evaluated when the <i>defer</i> 1032 executes, not when the <i>call</i> executes. Besides avoiding worries 1033 about variables changing values as the function executes, this means 1034 that a single deferred call site can defer multiple function 1035 executions. Here's a silly example. 1036 </p> 1037 1038 <pre> 1039 for i := 0; i < 5; i++ { 1040 defer fmt.Printf("%d ", i) 1041 } 1042 </pre> 1043 1044 <p> 1045 Deferred functions are executed in LIFO order, so this code will cause 1046 <code>4 3 2 1 0</code> to be printed when the function returns. A 1047 more plausible example is a simple way to trace function execution 1048 through the program. We could write a couple of simple tracing 1049 routines like this: 1050 </p> 1051 1052 <pre> 1053 func trace(s string) { fmt.Println("entering:", s) } 1054 func untrace(s string) { fmt.Println("leaving:", s) } 1055 1056 // Use them like this: 1057 func a() { 1058 trace("a") 1059 defer untrace("a") 1060 // do something.... 1061 } 1062 </pre> 1063 1064 <p> 1065 We can do better by exploiting the fact that arguments to deferred 1066 functions are evaluated when the <code>defer</code> executes. The 1067 tracing routine can set up the argument to the untracing routine. 1068 This example: 1069 </p> 1070 1071 <pre> 1072 func trace(s string) string { 1073 fmt.Println("entering:", s) 1074 return s 1075 } 1076 1077 func un(s string) { 1078 fmt.Println("leaving:", s) 1079 } 1080 1081 func a() { 1082 defer un(trace("a")) 1083 fmt.Println("in a") 1084 } 1085 1086 func b() { 1087 defer un(trace("b")) 1088 fmt.Println("in b") 1089 a() 1090 } 1091 1092 func main() { 1093 b() 1094 } 1095 </pre> 1096 1097 <p> 1098 prints 1099 </p> 1100 1101 <pre> 1102 entering: b 1103 in b 1104 entering: a 1105 in a 1106 leaving: a 1107 leaving: b 1108 </pre> 1109 1110 <p> 1111 For programmers accustomed to block-level resource management from 1112 other languages, <code>defer</code> may seem peculiar, but its most 1113 interesting and powerful applications come precisely from the fact 1114 that it's not block-based but function-based. In the section on 1115 <code>panic</code> and <code>recover</code> we'll see another 1116 example of its possibilities. 1117 </p> 1118 1119 <h2 id="data">Data</h2> 1120 1121 <h3 id="allocation_new">Allocation with <code>new</code></h3> 1122 1123 <p> 1124 Go has two allocation primitives, the built-in functions 1125 <code>new</code> and <code>make</code>. 1126 They do different things and apply to different types, which can be confusing, 1127 but the rules are simple. 1128 Let's talk about <code>new</code> first. 1129 It's a built-in function that allocates memory, but unlike its namesakes 1130 in some other languages it does not <em>initialize</em> the memory, 1131 it only <em>zeros</em> it. 1132 That is, 1133 <code>new(T)</code> allocates zeroed storage for a new item of type 1134 <code>T</code> and returns its address, a value of type <code>*T</code>. 1135 In Go terminology, it returns a pointer to a newly allocated zero value of type 1136 <code>T</code>. 1137 </p> 1138 1139 <p> 1140 Since the memory returned by <code>new</code> is zeroed, it's helpful to arrange 1141 when designing your data structures that the 1142 zero value of each type can be used without further initialization. This means a user of 1143 the data structure can create one with <code>new</code> and get right to 1144 work. 1145 For example, the documentation for <code>bytes.Buffer</code> states that 1146 "the zero value for <code>Buffer</code> is an empty buffer ready to use." 1147 Similarly, <code>sync.Mutex</code> does not 1148 have an explicit constructor or <code>Init</code> method. 1149 Instead, the zero value for a <code>sync.Mutex</code> 1150 is defined to be an unlocked mutex. 1151 </p> 1152 1153 <p> 1154 The zero-value-is-useful property works transitively. Consider this type declaration. 1155 </p> 1156 1157 <pre> 1158 type SyncedBuffer struct { 1159 lock sync.Mutex 1160 buffer bytes.Buffer 1161 } 1162 </pre> 1163 1164 <p> 1165 Values of type <code>SyncedBuffer</code> are also ready to use immediately upon allocation 1166 or just declaration. In the next snippet, both <code>p</code> and <code>v</code> will work 1167 correctly without further arrangement. 1168 </p> 1169 1170 <pre> 1171 p := new(SyncedBuffer) // type *SyncedBuffer 1172 var v SyncedBuffer // type SyncedBuffer 1173 </pre> 1174 1175 <h3 id="composite_literals">Constructors and composite literals</h3> 1176 1177 <p> 1178 Sometimes the zero value isn't good enough and an initializing 1179 constructor is necessary, as in this example derived from 1180 package <code>os</code>. 1181 </p> 1182 1183 <pre> 1184 func NewFile(fd int, name string) *File { 1185 if fd < 0 { 1186 return nil 1187 } 1188 f := new(File) 1189 f.fd = fd 1190 f.name = name 1191 f.dirinfo = nil 1192 f.nepipe = 0 1193 return f 1194 } 1195 </pre> 1196 1197 <p> 1198 There's a lot of boiler plate in there. We can simplify it 1199 using a <i>composite literal</i>, which is 1200 an expression that creates a 1201 new instance each time it is evaluated. 1202 </p> 1203 1204 <pre> 1205 func NewFile(fd int, name string) *File { 1206 if fd < 0 { 1207 return nil 1208 } 1209 f := File{fd, name, nil, 0} 1210 return &f 1211 } 1212 </pre> 1213 1214 <p> 1215 Note that, unlike in C, it's perfectly OK to return the address of a local variable; 1216 the storage associated with the variable survives after the function 1217 returns. 1218 In fact, taking the address of a composite literal 1219 allocates a fresh instance each time it is evaluated, 1220 so we can combine these last two lines. 1221 </p> 1222 1223 <pre> 1224 return &File{fd, name, nil, 0} 1225 </pre> 1226 1227 <p> 1228 The fields of a composite literal are laid out in order and must all be present. 1229 However, by labeling the elements explicitly as <i>field</i><code>:</code><i>value</i> 1230 pairs, the initializers can appear in any 1231 order, with the missing ones left as their respective zero values. Thus we could say 1232 </p> 1233 1234 <pre> 1235 return &File{fd: fd, name: name} 1236 </pre> 1237 1238 <p> 1239 As a limiting case, if a composite literal contains no fields at all, it creates 1240 a zero value for the type. The expressions <code>new(File)</code> and <code>&File{}</code> are equivalent. 1241 </p> 1242 1243 <p> 1244 Composite literals can also be created for arrays, slices, and maps, 1245 with the field labels being indices or map keys as appropriate. 1246 In these examples, the initializations work regardless of the values of <code>Enone</code>, 1247 <code>Eio</code>, and <code>Einval</code>, as long as they are distinct. 1248 </p> 1249 1250 <pre> 1251 a := [...]string {Enone: "no error", Eio: "Eio", Einval: "invalid argument"} 1252 s := []string {Enone: "no error", Eio: "Eio", Einval: "invalid argument"} 1253 m := map[int]string{Enone: "no error", Eio: "Eio", Einval: "invalid argument"} 1254 </pre> 1255 1256 <h3 id="allocation_make">Allocation with <code>make</code></h3> 1257 1258 <p> 1259 Back to allocation. 1260 The built-in function <code>make(T, </code><i>args</i><code>)</code> serves 1261 a purpose different from <code>new(T)</code>. 1262 It creates slices, maps, and channels only, and it returns an <em>initialized</em> 1263 (not <em>zeroed</em>) 1264 value of type <code>T</code> (not <code>*T</code>). 1265 The reason for the distinction 1266 is that these three types represent, under the covers, references to data structures that 1267 must be initialized before use. 1268 A slice, for example, is a three-item descriptor 1269 containing a pointer to the data (inside an array), the length, and the 1270 capacity, and until those items are initialized, the slice is <code>nil</code>. 1271 For slices, maps, and channels, 1272 <code>make</code> initializes the internal data structure and prepares 1273 the value for use. 1274 For instance, 1275 </p> 1276 1277 <pre> 1278 make([]int, 10, 100) 1279 </pre> 1280 1281 <p> 1282 allocates an array of 100 ints and then creates a slice 1283 structure with length 10 and a capacity of 100 pointing at the first 1284 10 elements of the array. 1285 (When making a slice, the capacity can be omitted; see the section on slices 1286 for more information.) 1287 In contrast, <code>new([]int)</code> returns a pointer to a newly allocated, zeroed slice 1288 structure, that is, a pointer to a <code>nil</code> slice value. 1289 </p> 1290 1291 <p> 1292 These examples illustrate the difference between <code>new</code> and 1293 <code>make</code>. 1294 </p> 1295 1296 <pre> 1297 var p *[]int = new([]int) // allocates slice structure; *p == nil; rarely useful 1298 var v []int = make([]int, 100) // the slice v now refers to a new array of 100 ints 1299 1300 // Unnecessarily complex: 1301 var p *[]int = new([]int) 1302 *p = make([]int, 100, 100) 1303 1304 // Idiomatic: 1305 v := make([]int, 100) 1306 </pre> 1307 1308 <p> 1309 Remember that <code>make</code> applies only to maps, slices and channels 1310 and does not return a pointer. 1311 To obtain an explicit pointer allocate with <code>new</code> or take the address 1312 of a variable explicitly. 1313 </p> 1314 1315 <h3 id="arrays">Arrays</h3> 1316 1317 <p> 1318 Arrays are useful when planning the detailed layout of memory and sometimes 1319 can help avoid allocation, but primarily 1320 they are a building block for slices, the subject of the next section. 1321 To lay the foundation for that topic, here are a few words about arrays. 1322 </p> 1323 1324 <p> 1325 There are major differences between the ways arrays work in Go and C. 1326 In Go, 1327 </p> 1328 <ul> 1329 <li> 1330 Arrays are values. Assigning one array to another copies all the elements. 1331 </li> 1332 <li> 1333 In particular, if you pass an array to a function, it 1334 will receive a <i>copy</i> of the array, not a pointer to it. 1335 <li> 1336 The size of an array is part of its type. The types <code>[10]int</code> 1337 and <code>[20]int</code> are distinct. 1338 </li> 1339 </ul> 1340 1341 <p> 1342 The value property can be useful but also expensive; if you want C-like behavior and efficiency, 1343 you can pass a pointer to the array. 1344 </p> 1345 1346 <pre> 1347 func Sum(a *[3]float64) (sum float64) { 1348 for _, v := range *a { 1349 sum += v 1350 } 1351 return 1352 } 1353 1354 array := [...]float64{7.0, 8.5, 9.1} 1355 x := Sum(&array) // Note the explicit address-of operator 1356 </pre> 1357 1358 <p> 1359 But even this style isn't idiomatic Go. 1360 Use slices instead. 1361 </p> 1362 1363 <h3 id="slices">Slices</h3> 1364 1365 <p> 1366 Slices wrap arrays to give a more general, powerful, and convenient 1367 interface to sequences of data. Except for items with explicit 1368 dimension such as transformation matrices, most array programming in 1369 Go is done with slices rather than simple arrays. 1370 </p> 1371 <p> 1372 Slices hold references to an underlying array, and if you assign one 1373 slice to another, both refer to the same array. 1374 If a function takes a slice argument, changes it makes to 1375 the elements of the slice will be visible to the caller, analogous to 1376 passing a pointer to the underlying array. A <code>Read</code> 1377 function can therefore accept a slice argument rather than a pointer 1378 and a count; the length within the slice sets an upper 1379 limit of how much data to read. Here is the signature of the 1380 <code>Read</code> method of the <code>File</code> type in package 1381 <code>os</code>: 1382 </p> 1383 <pre> 1384 func (file *File) Read(buf []byte) (n int, err error) 1385 </pre> 1386 <p> 1387 The method returns the number of bytes read and an error value, if 1388 any. To read into the first 32 bytes of a larger buffer 1389 <code>b</code>, <i>slice</i> (here used as a verb) the buffer. 1390 </p> 1391 <pre> 1392 n, err := f.Read(buf[0:32]) 1393 </pre> 1394 <p> 1395 Such slicing is common and efficient. In fact, leaving efficiency aside for 1396 the moment, the following snippet would also read the first 32 bytes of the buffer. 1397 </p> 1398 <pre> 1399 var n int 1400 var err error 1401 for i := 0; i < 32; i++ { 1402 nbytes, e := f.Read(buf[i:i+1]) // Read one byte. 1403 if nbytes == 0 || e != nil { 1404 err = e 1405 break 1406 } 1407 n += nbytes 1408 } 1409 </pre> 1410 <p> 1411 The length of a slice may be changed as long as it still fits within 1412 the limits of the underlying array; just assign it to a slice of 1413 itself. The <i>capacity</i> of a slice, accessible by the built-in 1414 function <code>cap</code>, reports the maximum length the slice may 1415 assume. Here is a function to append data to a slice. If the data 1416 exceeds the capacity, the slice is reallocated. The 1417 resulting slice is returned. The function uses the fact that 1418 <code>len</code> and <code>cap</code> are legal when applied to the 1419 <code>nil</code> slice, and return 0. 1420 </p> 1421 <pre> 1422 func Append(slice, data[]byte) []byte { 1423 l := len(slice) 1424 if l + len(data) > cap(slice) { // reallocate 1425 // Allocate double what's needed, for future growth. 1426 newSlice := make([]byte, (l+len(data))*2) 1427 // The copy function is predeclared and works for any slice type. 1428 copy(newSlice, slice) 1429 slice = newSlice 1430 } 1431 slice = slice[0:l+len(data)] 1432 for i, c := range data { 1433 slice[l+i] = c 1434 } 1435 return slice 1436 } 1437 </pre> 1438 <p> 1439 We must return the slice afterwards because, although <code>Append</code> 1440 can modify the elements of <code>slice</code>, the slice itself (the run-time data 1441 structure holding the pointer, length, and capacity) is passed by value. 1442 </p> 1443 1444 <p> 1445 The idea of appending to a slice is so useful it's captured by the 1446 <code>append</code> built-in function. To understand that function's 1447 design, though, we need a little more information, so we'll return 1448 to it later. 1449 </p> 1450 1451 <h3 id="two_dimensional_slices">Two-dimensional slices</h3> 1452 1453 <p> 1454 Go's arrays and slices are one-dimensional. 1455 To create the equivalent of a 2D array or slice, it is necessary to define an array-of-arrays 1456 or slice-of-slices, like this: 1457 </p> 1458 1459 <pre> 1460 type Transform [3][3]float64 // A 3x3 array, really an array of arrays. 1461 type LinesOfText [][]byte // A slice of byte slices. 1462 </pre> 1463 1464 <p> 1465 Because slices are variable-length, it is possible to have each inner 1466 slice be a different length. 1467 That can be a common situation, as in our <code>LinesOfText</code> 1468 example: each line has an independent length. 1469 </p> 1470 1471 <pre> 1472 text := LinesOfText{ 1473 []byte("Now is the time"), 1474 []byte("for all good gophers"), 1475 []byte("to bring some fun to the party."), 1476 } 1477 </pre> 1478 1479 <p> 1480 Sometimes it's necessary to allocate a 2D slice, a situation that can arise when 1481 processing scan lines of pixels, for instance. 1482 There are two ways to achieve this. 1483 One is to allocate each slice independently; the other 1484 is to allocate a single array and point the individual slices into it. 1485 Which to use depends on your application. 1486 If the slices might grow or shrink, they should be allocated independently 1487 to avoid overwriting the next line; if not, it can be more efficient to construct 1488 the object with a single allocation. 1489 For reference, here are sketches of the two methods. 1490 First, a line a time: 1491 </p> 1492 1493 <pre> 1494 // Allocate the top-level slice. 1495 picture := make([][]uint8, YSize) // One row per unit of y. 1496 // Loop over the rows, allocating the slice for each row. 1497 for i := range picture { 1498 picture[i] = make([]uint8, XSize) 1499 } 1500 </pre> 1501 1502 <p> 1503 And now as one allocation, sliced into lines: 1504 </p> 1505 1506 <pre> 1507 // Allocate the top-level slice, the same as before. 1508 picture := make([][]uint8, YSize) // One row per unit of y. 1509 // Allocate one large slice to hold all the pixels. 1510 pixels := make([]uint8, XSize*YSize) // Has type []uint8 even though picture is [][]uint8. 1511 // Loop over the rows, slicing each row from the front of the remaining pixels slice. 1512 for i := range picture { 1513 picture[i], pixels = pixels[:XSize], pixels[XSize:] 1514 } 1515 </pre> 1516 1517 <h3 id="maps">Maps</h3> 1518 1519 <p> 1520 Maps are a convenient and powerful built-in data structure that associate 1521 values of one type (the <em>key</em>) with values of another type 1522 (the <em>element</em> or <em>value</em>) 1523 The key can be of any type for which the equality operator is defined, 1524 such as integers, 1525 floating point and complex numbers, 1526 strings, pointers, interfaces (as long as the dynamic type 1527 supports equality), structs and arrays. 1528 Slices cannot be used as map keys, 1529 because equality is not defined on them. 1530 Like slices, maps hold references to an underlying data structure. 1531 If you pass a map to a function 1532 that changes the contents of the map, the changes will be visible 1533 in the caller. 1534 </p> 1535 <p> 1536 Maps can be constructed using the usual composite literal syntax 1537 with colon-separated key-value pairs, 1538 so it's easy to build them during initialization. 1539 </p> 1540 <pre> 1541 var timeZone = map[string]int{ 1542 "UTC": 0*60*60, 1543 "EST": -5*60*60, 1544 "CST": -6*60*60, 1545 "MST": -7*60*60, 1546 "PST": -8*60*60, 1547 } 1548 </pre> 1549 <p> 1550 Assigning and fetching map values looks syntactically just like 1551 doing the same for arrays and slices except that the index doesn't 1552 need to be an integer. 1553 </p> 1554 <pre> 1555 offset := timeZone["EST"] 1556 </pre> 1557 <p> 1558 An attempt to fetch a map value with a key that 1559 is not present in the map will return the zero value for the type 1560 of the entries 1561 in the map. For instance, if the map contains integers, looking 1562 up a non-existent key will return <code>0</code>. 1563 A set can be implemented as a map with value type <code>bool</code>. 1564 Set the map entry to <code>true</code> to put the value in the set, and then 1565 test it by simple indexing. 1566 </p> 1567 <pre> 1568 attended := map[string]bool{ 1569 "Ann": true, 1570 "Joe": true, 1571 ... 1572 } 1573 1574 if attended[person] { // will be false if person is not in the map 1575 fmt.Println(person, "was at the meeting") 1576 } 1577 </pre> 1578 <p> 1579 Sometimes you need to distinguish a missing entry from 1580 a zero value. Is there an entry for <code>"UTC"</code> 1581 or is that the empty string because it's not in the map at all? 1582 You can discriminate with a form of multiple assignment. 1583 </p> 1584 <pre> 1585 var seconds int 1586 var ok bool 1587 seconds, ok = timeZone[tz] 1588 </pre> 1589 <p> 1590 For obvious reasons this is called the “comma ok” idiom. 1591 In this example, if <code>tz</code> is present, <code>seconds</code> 1592 will be set appropriately and <code>ok</code> will be true; if not, 1593 <code>seconds</code> will be set to zero and <code>ok</code> will 1594 be false. 1595 Here's a function that puts it together with a nice error report: 1596 </p> 1597 <pre> 1598 func offset(tz string) int { 1599 if seconds, ok := timeZone[tz]; ok { 1600 return seconds 1601 } 1602 log.Println("unknown time zone:", tz) 1603 return 0 1604 } 1605 </pre> 1606 <p> 1607 To test for presence in the map without worrying about the actual value, 1608 you can use the <a href="#blank">blank identifier</a> (<code>_</code>) 1609 in place of the usual variable for the value. 1610 </p> 1611 <pre> 1612 _, present := timeZone[tz] 1613 </pre> 1614 <p> 1615 To delete a map entry, use the <code>delete</code> 1616 built-in function, whose arguments are the map and the key to be deleted. 1617 It's safe to do this even if the key is already absent 1618 from the map. 1619 </p> 1620 <pre> 1621 delete(timeZone, "PDT") // Now on Standard Time 1622 </pre> 1623 1624 <h3 id="printing">Printing</h3> 1625 1626 <p> 1627 Formatted printing in Go uses a style similar to C's <code>printf</code> 1628 family but is richer and more general. The functions live in the <code>fmt</code> 1629 package and have capitalized names: <code>fmt.Printf</code>, <code>fmt.Fprintf</code>, 1630 <code>fmt.Sprintf</code> and so on. The string functions (<code>Sprintf</code> etc.) 1631 return a string rather than filling in a provided buffer. 1632 </p> 1633 <p> 1634 You don't need to provide a format string. For each of <code>Printf</code>, 1635 <code>Fprintf</code> and <code>Sprintf</code> there is another pair 1636 of functions, for instance <code>Print</code> and <code>Println</code>. 1637 These functions do not take a format string but instead generate a default 1638 format for each argument. The <code>Println</code> versions also insert a blank 1639 between arguments and append a newline to the output while 1640 the <code>Print</code> versions add blanks only if the operand on neither side is a string. 1641 In this example each line produces the same output. 1642 </p> 1643 <pre> 1644 fmt.Printf("Hello %d\n", 23) 1645 fmt.Fprint(os.Stdout, "Hello ", 23, "\n") 1646 fmt.Println("Hello", 23) 1647 fmt.Println(fmt.Sprint("Hello ", 23)) 1648 </pre> 1649 <p> 1650 The formatted print functions <code>fmt.Fprint</code> 1651 and friends take as a first argument any object 1652 that implements the <code>io.Writer</code> interface; the variables <code>os.Stdout</code> 1653 and <code>os.Stderr</code> are familiar instances. 1654 </p> 1655 <p> 1656 Here things start to diverge from C. First, the numeric formats such as <code>%d</code> 1657 do not take flags for signedness or size; instead, the printing routines use the 1658 type of the argument to decide these properties. 1659 </p> 1660 <pre> 1661 var x uint64 = 1<<64 - 1 1662 fmt.Printf("%d %x; %d %x\n", x, x, int64(x), int64(x)) 1663 </pre> 1664 <p> 1665 prints 1666 </p> 1667 <pre> 1668 18446744073709551615 ffffffffffffffff; -1 -1 1669 </pre> 1670 <p> 1671 If you just want the default conversion, such as decimal for integers, you can use 1672 the catchall format <code>%v</code> (for “value”); the result is exactly 1673 what <code>Print</code> and <code>Println</code> would produce. 1674 Moreover, that format can print <em>any</em> value, even arrays, slices, structs, and 1675 maps. Here is a print statement for the time zone map defined in the previous section. 1676 </p> 1677 <pre> 1678 fmt.Printf("%v\n", timeZone) // or just fmt.Println(timeZone) 1679 </pre> 1680 <p> 1681 which gives output 1682 </p> 1683 <pre> 1684 map[CST:-21600 PST:-28800 EST:-18000 UTC:0 MST:-25200] 1685 </pre> 1686 <p> 1687 For maps the keys may be output in any order, of course. 1688 When printing a struct, the modified format <code>%+v</code> annotates the 1689 fields of the structure with their names, and for any value the alternate 1690 format <code>%#v</code> prints the value in full Go syntax. 1691 </p> 1692 <pre> 1693 type T struct { 1694 a int 1695 b float64 1696 c string 1697 } 1698 t := &T{ 7, -2.35, "abc\tdef" } 1699 fmt.Printf("%v\n", t) 1700 fmt.Printf("%+v\n", t) 1701 fmt.Printf("%#v\n", t) 1702 fmt.Printf("%#v\n", timeZone) 1703 </pre> 1704 <p> 1705 prints 1706 </p> 1707 <pre> 1708 &{7 -2.35 abc def} 1709 &{a:7 b:-2.35 c:abc def} 1710 &main.T{a:7, b:-2.35, c:"abc\tdef"} 1711 map[string] int{"CST":-21600, "PST":-28800, "EST":-18000, "UTC":0, "MST":-25200} 1712 </pre> 1713 <p> 1714 (Note the ampersands.) 1715 That quoted string format is also available through <code>%q</code> when 1716 applied to a value of type <code>string</code> or <code>[]byte</code>. 1717 The alternate format <code>%#q</code> will use backquotes instead if possible. 1718 (The <code>%q</code> format also applies to integers and runes, producing a 1719 single-quoted rune constant.) 1720 Also, <code>%x</code> works on strings, byte arrays and byte slices as well as 1721 on integers, generating a long hexadecimal string, and with 1722 a space in the format (<code>% x</code>) it puts spaces between the bytes. 1723 </p> 1724 <p> 1725 Another handy format is <code>%T</code>, which prints the <em>type</em> of a value. 1726 </p> 1727 <pre> 1728 fmt.Printf("%T\n", timeZone) 1729 </pre> 1730 <p> 1731 prints 1732 </p> 1733 <pre> 1734 map[string] int 1735 </pre> 1736 <p> 1737 If you want to control the default format for a custom type, all that's required is to define 1738 a method with the signature <code>String() string</code> on the type. 1739 For our simple type <code>T</code>, that might look like this. 1740 </p> 1741 <pre> 1742 func (t *T) String() string { 1743 return fmt.Sprintf("%d/%g/%q", t.a, t.b, t.c) 1744 } 1745 fmt.Printf("%v\n", t) 1746 </pre> 1747 <p> 1748 to print in the format 1749 </p> 1750 <pre> 1751 7/-2.35/"abc\tdef" 1752 </pre> 1753 <p> 1754 (If you need to print <em>values</em> of type <code>T</code> as well as pointers to <code>T</code>, 1755 the receiver for <code>String</code> must be of value type; this example used a pointer because 1756 that's more efficient and idiomatic for struct types. 1757 See the section below on <a href="#pointers_vs_values">pointers vs. value receivers</a> for more information.) 1758 </p> 1759 1760 <p> 1761 Our <code>String</code> method is able to call <code>Sprintf</code> because the 1762 print routines are fully reentrant and can be wrapped this way. 1763 There is one important detail to understand about this approach, 1764 however: don't construct a <code>String</code> method by calling 1765 <code>Sprintf</code> in a way that will recur into your <code>String</code> 1766 method indefinitely. This can happen if the <code>Sprintf</code> 1767 call attempts to print the receiver directly as a string, which in 1768 turn will invoke the method again. It's a common and easy mistake 1769 to make, as this example shows. 1770 </p> 1771 1772 <pre> 1773 type MyString string 1774 1775 func (m MyString) String() string { 1776 return fmt.Sprintf("MyString=%s", m) // Error: will recur forever. 1777 } 1778 </pre> 1779 1780 <p> 1781 It's also easy to fix: convert the argument to the basic string type, which does not have the 1782 method. 1783 </p> 1784 1785 <pre> 1786 type MyString string 1787 func (m MyString) String() string { 1788 return fmt.Sprintf("MyString=%s", string(m)) // OK: note conversion. 1789 } 1790 </pre> 1791 1792 <p> 1793 In the <a href="#initialization">initialization section</a> we'll see another technique that avoids this recursion. 1794 </p> 1795 1796 <p> 1797 Another printing technique is to pass a print routine's arguments directly to another such routine. 1798 The signature of <code>Printf</code> uses the type <code>...interface{}</code> 1799 for its final argument to specify that an arbitrary number of parameters (of arbitrary type) 1800 can appear after the format. 1801 </p> 1802 <pre> 1803 func Printf(format string, v ...interface{}) (n int, err error) { 1804 </pre> 1805 <p> 1806 Within the function <code>Printf</code>, <code>v</code> acts like a variable of type 1807 <code>[]interface{}</code> but if it is passed to another variadic function, it acts like 1808 a regular list of arguments. 1809 Here is the implementation of the 1810 function <code>log.Println</code> we used above. It passes its arguments directly to 1811 <code>fmt.Sprintln</code> for the actual formatting. 1812 </p> 1813 <pre> 1814 // Println prints to the standard logger in the manner of fmt.Println. 1815 func Println(v ...interface{}) { 1816 std.Output(2, fmt.Sprintln(v...)) // Output takes parameters (int, string) 1817 } 1818 </pre> 1819 <p> 1820 We write <code>...</code> after <code>v</code> in the nested call to <code>Sprintln</code> to tell the 1821 compiler to treat <code>v</code> as a list of arguments; otherwise it would just pass 1822 <code>v</code> as a single slice argument. 1823 </p> 1824 <p> 1825 There's even more to printing than we've covered here. See the <code>godoc</code> documentation 1826 for package <code>fmt</code> for the details. 1827 </p> 1828 <p> 1829 By the way, a <code>...</code> parameter can be of a specific type, for instance <code>...int</code> 1830 for a min function that chooses the least of a list of integers: 1831 </p> 1832 <pre> 1833 func Min(a ...int) int { 1834 min := int(^uint(0) >> 1) // largest int 1835 for _, i := range a { 1836 if i < min { 1837 min = i 1838 } 1839 } 1840 return min 1841 } 1842 </pre> 1843 1844 <h3 id="append">Append</h3> 1845 <p> 1846 Now we have the missing piece we needed to explain the design of 1847 the <code>append</code> built-in function. The signature of <code>append</code> 1848 is different from our custom <code>Append</code> function above. 1849 Schematically, it's like this: 1850 </p> 1851 <pre> 1852 func append(slice []<i>T</i>, elements ...<i>T</i>) []<i>T</i> 1853 </pre> 1854 <p> 1855 where <i>T</i> is a placeholder for any given type. You can't 1856 actually write a function in Go where the type <code>T</code> 1857 is determined by the caller. 1858 That's why <code>append</code> is built in: it needs support from the 1859 compiler. 1860 </p> 1861 <p> 1862 What <code>append</code> does is append the elements to the end of 1863 the slice and return the result. The result needs to be returned 1864 because, as with our hand-written <code>Append</code>, the underlying 1865 array may change. This simple example 1866 </p> 1867 <pre> 1868 x := []int{1,2,3} 1869 x = append(x, 4, 5, 6) 1870 fmt.Println(x) 1871 </pre> 1872 <p> 1873 prints <code>[1 2 3 4 5 6]</code>. So <code>append</code> works a 1874 little like <code>Printf</code>, collecting an arbitrary number of 1875 arguments. 1876 </p> 1877 <p> 1878 But what if we wanted to do what our <code>Append</code> does and 1879 append a slice to a slice? Easy: use <code>...</code> at the call 1880 site, just as we did in the call to <code>Output</code> above. This 1881 snippet produces identical output to the one above. 1882 </p> 1883 <pre> 1884 x := []int{1,2,3} 1885 y := []int{4,5,6} 1886 x = append(x, y...) 1887 fmt.Println(x) 1888 </pre> 1889 <p> 1890 Without that <code>...</code>, it wouldn't compile because the types 1891 would be wrong; <code>y</code> is not of type <code>int</code>. 1892 </p> 1893 1894 <h2 id="initialization">Initialization</h2> 1895 1896 <p> 1897 Although it doesn't look superficially very different from 1898 initialization in C or C++, initialization in Go is more powerful. 1899 Complex structures can be built during initialization and the ordering 1900 issues among initialized objects, even among different packages, are handled 1901 correctly. 1902 </p> 1903 1904 <h3 id="constants">Constants</h3> 1905 1906 <p> 1907 Constants in Go are just that—constant. 1908 They are created at compile time, even when defined as 1909 locals in functions, 1910 and can only be numbers, characters (runes), strings or booleans. 1911 Because of the compile-time restriction, the expressions 1912 that define them must be constant expressions, 1913 evaluatable by the compiler. For instance, 1914 <code>1<<3</code> is a constant expression, while 1915 <code>math.Sin(math.Pi/4)</code> is not because 1916 the function call to <code>math.Sin</code> needs 1917 to happen at run time. 1918 </p> 1919 1920 <p> 1921 In Go, enumerated constants are created using the <code>iota</code> 1922 enumerator. Since <code>iota</code> can be part of an expression and 1923 expressions can be implicitly repeated, it is easy to build intricate 1924 sets of values. 1925 </p> 1926 {{code "/doc/progs/eff_bytesize.go" `/^type ByteSize/` `/^\)/`}} 1927 <p> 1928 The ability to attach a method such as <code>String</code> to any 1929 user-defined type makes it possible for arbitrary values to format themselves 1930 automatically for printing. 1931 Although you'll see it most often applied to structs, this technique is also useful for 1932 scalar types such as floating-point types like <code>ByteSize</code>. 1933 </p> 1934 {{code "/doc/progs/eff_bytesize.go" `/^func.*ByteSize.*String/` `/^}/`}} 1935 <p> 1936 The expression <code>YB</code> prints as <code>1.00YB</code>, 1937 while <code>ByteSize(1e13)</code> prints as <code>9.09TB</code>. 1938 </p> 1939 1940 <p> 1941 The use here of <code>Sprintf</code> 1942 to implement <code>ByteSize</code>'s <code>String</code> method is safe 1943 (avoids recurring indefinitely) not because of a conversion but 1944 because it calls <code>Sprintf</code> with <code>%f</code>, 1945 which is not a string format: <code>Sprintf</code> will only call 1946 the <code>String</code> method when it wants a string, and <code>%f</code> 1947 wants a floating-point value. 1948 </p> 1949 1950 <h3 id="variables">Variables</h3> 1951 1952 <p> 1953 Variables can be initialized just like constants but the 1954 initializer can be a general expression computed at run time. 1955 </p> 1956 <pre> 1957 var ( 1958 home = os.Getenv("HOME") 1959 user = os.Getenv("USER") 1960 gopath = os.Getenv("GOPATH") 1961 ) 1962 </pre> 1963 1964 <h3 id="init">The init function</h3> 1965 1966 <p> 1967 Finally, each source file can define its own niladic <code>init</code> function to 1968 set up whatever state is required. (Actually each file can have multiple 1969 <code>init</code> functions.) 1970 And finally means finally: <code>init</code> is called after all the 1971 variable declarations in the package have evaluated their initializers, 1972 and those are evaluated only after all the imported packages have been 1973 initialized. 1974 </p> 1975 <p> 1976 Besides initializations that cannot be expressed as declarations, 1977 a common use of <code>init</code> functions is to verify or repair 1978 correctness of the program state before real execution begins. 1979 </p> 1980 1981 <pre> 1982 func init() { 1983 if user == "" { 1984 log.Fatal("$USER not set") 1985 } 1986 if home == "" { 1987 home = "/home/" + user 1988 } 1989 if gopath == "" { 1990 gopath = home + "/go" 1991 } 1992 // gopath may be overridden by --gopath flag on command line. 1993 flag.StringVar(&gopath, "gopath", gopath, "override default GOPATH") 1994 } 1995 </pre> 1996 1997 <h2 id="methods">Methods</h2> 1998 1999 <h3 id="pointers_vs_values">Pointers vs. Values</h3> 2000 <p> 2001 As we saw with <code>ByteSize</code>, 2002 methods can be defined for any named type (except a pointer or an interface); 2003 the receiver does not have to be a struct. 2004 </p> 2005 <p> 2006 In the discussion of slices above, we wrote an <code>Append</code> 2007 function. We can define it as a method on slices instead. To do 2008 this, we first declare a named type to which we can bind the method, and 2009 then make the receiver for the method a value of that type. 2010 </p> 2011 <pre> 2012 type ByteSlice []byte 2013 2014 func (slice ByteSlice) Append(data []byte) []byte { 2015 // Body exactly the same as above 2016 } 2017 </pre> 2018 <p> 2019 This still requires the method to return the updated slice. We can 2020 eliminate that clumsiness by redefining the method to take a 2021 <i>pointer</i> to a <code>ByteSlice</code> as its receiver, so the 2022 method can overwrite the caller's slice. 2023 </p> 2024 <pre> 2025 func (p *ByteSlice) Append(data []byte) { 2026 slice := *p 2027 // Body as above, without the return. 2028 *p = slice 2029 } 2030 </pre> 2031 <p> 2032 In fact, we can do even better. If we modify our function so it looks 2033 like a standard <code>Write</code> method, like this, 2034 </p> 2035 <pre> 2036 func (p *ByteSlice) Write(data []byte) (n int, err error) { 2037 slice := *p 2038 // Again as above. 2039 *p = slice 2040 return len(data), nil 2041 } 2042 </pre> 2043 <p> 2044 then the type <code>*ByteSlice</code> satisfies the standard interface 2045 <code>io.Writer</code>, which is handy. For instance, we can 2046 print into one. 2047 </p> 2048 <pre> 2049 var b ByteSlice 2050 fmt.Fprintf(&b, "This hour has %d days\n", 7) 2051 </pre> 2052 <p> 2053 We pass the address of a <code>ByteSlice</code> 2054 because only <code>*ByteSlice</code> satisfies <code>io.Writer</code>. 2055 The rule about pointers vs. values for receivers is that value methods 2056 can be invoked on pointers and values, but pointer methods can only be 2057 invoked on pointers. This is because pointer methods can modify the 2058 receiver; invoking them on a copy of the value would cause those 2059 modifications to be discarded. 2060 </p> 2061 <p> 2062 By the way, the idea of using <code>Write</code> on a slice of bytes 2063 is central to the implementation of <code>bytes.Buffer</code>. 2064 </p> 2065 2066 <h2 id="interfaces_and_types">Interfaces and other types</h2> 2067 2068 <h3 id="interfaces">Interfaces</h3> 2069 <p> 2070 Interfaces in Go provide a way to specify the behavior of an 2071 object: if something can do <em>this</em>, then it can be used 2072 <em>here</em>. We've seen a couple of simple examples already; 2073 custom printers can be implemented by a <code>String</code> method 2074 while <code>Fprintf</code> can generate output to anything 2075 with a <code>Write</code> method. 2076 Interfaces with only one or two methods are common in Go code, and are 2077 usually given a name derived from the method, such as <code>io.Writer</code> 2078 for something that implements <code>Write</code>. 2079 </p> 2080 <p> 2081 A type can implement multiple interfaces. 2082 For instance, a collection can be sorted 2083 by the routines in package <code>sort</code> if it implements 2084 <code>sort.Interface</code>, which contains <code>Len()</code>, 2085 <code>Less(i, j int) bool</code>, and <code>Swap(i, j int)</code>, 2086 and it could also have a custom formatter. 2087 In this contrived example <code>Sequence</code> satisfies both. 2088 </p> 2089 {{code "/doc/progs/eff_sequence.go" `/^type/` "$"}} 2090 2091 <h3 id="conversions">Conversions</h3> 2092 2093 <p> 2094 The <code>String</code> method of <code>Sequence</code> is recreating the 2095 work that <code>Sprint</code> already does for slices. We can share the 2096 effort if we convert the <code>Sequence</code> to a plain 2097 <code>[]int</code> before calling <code>Sprint</code>. 2098 </p> 2099 <pre> 2100 func (s Sequence) String() string { 2101 sort.Sort(s) 2102 return fmt.Sprint([]int(s)) 2103 } 2104 </pre> 2105 <p> 2106 This method is another example of the conversion technique for calling 2107 <code>Sprintf</code> safely from a <code>String</code> method. 2108 Because the two types (<code>Sequence</code> and <code>[]int</code>) 2109 are the same if we ignore the type name, it's legal to convert between them. 2110 The conversion doesn't create a new value, it just temporarily acts 2111 as though the existing value has a new type. 2112 (There are other legal conversions, such as from integer to floating point, that 2113 do create a new value.) 2114 </p> 2115 <p> 2116 It's an idiom in Go programs to convert the 2117 type of an expression to access a different 2118 set of methods. As an example, we could use the existing 2119 type <code>sort.IntSlice</code> to reduce the entire example 2120 to this: 2121 </p> 2122 <pre> 2123 type Sequence []int 2124 2125 // Method for printing - sorts the elements before printing 2126 func (s Sequence) String() string { 2127 sort.IntSlice(s).Sort() 2128 return fmt.Sprint([]int(s)) 2129 } 2130 </pre> 2131 <p> 2132 Now, instead of having <code>Sequence</code> implement multiple 2133 interfaces (sorting and printing), we're using the ability of a data item to be 2134 converted to multiple types (<code>Sequence</code>, <code>sort.IntSlice</code> 2135 and <code>[]int</code>), each of which does some part of the job. 2136 That's more unusual in practice but can be effective. 2137 </p> 2138 2139 <h3 id="interface_conversions">Interface conversions and type assertions</h3> 2140 2141 <p> 2142 <a href="#type_switch">Type switches</a> are a form of conversion: they take an interface and, for 2143 each case in the switch, in a sense convert it to the type of that case. 2144 Here's a simplified version of how the code under <code>fmt.Printf</code> turns a value into 2145 a string using a type switch. 2146 If it's already a string, we want the actual string value held by the interface, while if it has a 2147 <code>String</code> method we want the result of calling the method. 2148 </p> 2149 2150 <pre> 2151 type Stringer interface { 2152 String() string 2153 } 2154 2155 var value interface{} // Value provided by caller. 2156 switch str := value.(type) { 2157 case string: 2158 return str 2159 case Stringer: 2160 return str.String() 2161 } 2162 </pre> 2163 2164 <p> 2165 The first case finds a concrete value; the second converts the interface into another interface. 2166 It's perfectly fine to mix types this way. 2167 </p> 2168 2169 <p> 2170 What if there's only one type we care about? If we know the value holds a <code>string</code> 2171 and we just want to extract it? 2172 A one-case type switch would do, but so would a <em>type assertion</em>. 2173 A type assertion takes an interface value and extracts from it a value of the specified explicit type. 2174 The syntax borrows from the clause opening a type switch, but with an explicit 2175 type rather than the <code>type</code> keyword: 2176 2177 <pre> 2178 value.(typeName) 2179 </pre> 2180 2181 <p> 2182 and the result is a new value with the static type <code>typeName</code>. 2183 That type must either be the concrete type held by the interface, or a second interface 2184 type that the value can be converted to. 2185 To extract the string we know is in the value, we could write: 2186 </p> 2187 2188 <pre> 2189 str := value.(string) 2190 </pre> 2191 2192 <p> 2193 But if it turns out that the value does not contain a string, the program will crash with a run-time error. 2194 To guard against that, use the "comma, ok" idiom to test, safely, whether the value is a string: 2195 </p> 2196 2197 <pre> 2198 str, ok := value.(string) 2199 if ok { 2200 fmt.Printf("string value is: %q\n", str) 2201 } else { 2202 fmt.Printf("value is not a string\n") 2203 } 2204 </pre> 2205 2206 <p> 2207 If the type assertion fails, <code>str</code> will still exist and be of type string, but it will have 2208 the zero value, an empty string. 2209 </p> 2210 2211 <p> 2212 As an illustration of the capability, here's an <code>if</code>-<code>else</code> 2213 statement that's equivalent to the type switch that opened this section. 2214 </p> 2215 2216 <pre> 2217 if str, ok := value.(string); ok { 2218 return str 2219 } else if str, ok := value.(Stringer); ok { 2220 return str.String() 2221 } 2222 </pre> 2223 2224 <h3 id="generality">Generality</h3> 2225 <p> 2226 If a type exists only to implement an interface 2227 and has no exported methods beyond that interface, 2228 there is no need to export the type itself. 2229 Exporting just the interface makes it clear that 2230 it's the behavior that matters, not the implementation, 2231 and that other implementations with different properties 2232 can mirror the behavior of the original type. 2233 It also avoids the need to repeat the documentation 2234 on every instance of a common method. 2235 </p> 2236 <p> 2237 In such cases, the constructor should return an interface value 2238 rather than the implementing type. 2239 As an example, in the hash libraries 2240 both <code>crc32.NewIEEE</code> and <code>adler32.New</code> 2241 return the interface type <code>hash.Hash32</code>. 2242 Substituting the CRC-32 algorithm for Adler-32 in a Go program 2243 requires only changing the constructor call; 2244 the rest of the code is unaffected by the change of algorithm. 2245 </p> 2246 <p> 2247 A similar approach allows the streaming cipher algorithms 2248 in the various <code>crypto</code> packages to be 2249 separated from the block ciphers they chain together. 2250 The <code>Block</code> interface 2251 in the <code>crypto/cipher</code> package specifies the 2252 behavior of a block cipher, which provides encryption 2253 of a single block of data. 2254 Then, by analogy with the <code>bufio</code> package, 2255 cipher packages that implement this interface 2256 can be used to construct streaming ciphers, represented 2257 by the <code>Stream</code> interface, without 2258 knowing the details of the block encryption. 2259 </p> 2260 <p> 2261 The <code>crypto/cipher</code> interfaces look like this: 2262 </p> 2263 <pre> 2264 type Block interface { 2265 BlockSize() int 2266 Encrypt(src, dst []byte) 2267 Decrypt(src, dst []byte) 2268 } 2269 2270 type Stream interface { 2271 XORKeyStream(dst, src []byte) 2272 } 2273 </pre> 2274 2275 <p> 2276 Here's the definition of the counter mode (CTR) stream, 2277 which turns a block cipher into a streaming cipher; notice 2278 that the block cipher's details are abstracted away: 2279 </p> 2280 2281 <pre> 2282 // NewCTR returns a Stream that encrypts/decrypts using the given Block in 2283 // counter mode. The length of iv must be the same as the Block's block size. 2284 func NewCTR(block Block, iv []byte) Stream 2285 </pre> 2286 <p> 2287 <code>NewCTR</code> applies not 2288 just to one specific encryption algorithm and data source but to any 2289 implementation of the <code>Block</code> interface and any 2290 <code>Stream</code>. Because they return 2291 interface values, replacing CTR 2292 encryption with other encryption modes is a localized change. The constructor 2293 calls must be edited, but because the surrounding code must treat the result only 2294 as a <code>Stream</code>, it won't notice the difference. 2295 </p> 2296 2297 <h3 id="interface_methods">Interfaces and methods</h3> 2298 <p> 2299 Since almost anything can have methods attached, almost anything can 2300 satisfy an interface. One illustrative example is in the <code>http</code> 2301 package, which defines the <code>Handler</code> interface. Any object 2302 that implements <code>Handler</code> can serve HTTP requests. 2303 </p> 2304 <pre> 2305 type Handler interface { 2306 ServeHTTP(ResponseWriter, *Request) 2307 } 2308 </pre> 2309 <p> 2310 <code>ResponseWriter</code> is itself an interface that provides access 2311 to the methods needed to return the response to the client. 2312 Those methods include the standard <code>Write</code> method, so an 2313 <code>http.ResponseWriter</code> can be used wherever an <code>io.Writer</code> 2314 can be used. 2315 <code>Request</code> is a struct containing a parsed representation 2316 of the request from the client. 2317 </p> 2318 <p> 2319 For brevity, let's ignore POSTs and assume HTTP requests are always 2320 GETs; that simplification does not affect the way the handlers are 2321 set up. Here's a trivial but complete implementation of a handler to 2322 count the number of times the 2323 page is visited. 2324 </p> 2325 <pre> 2326 // Simple counter server. 2327 type Counter struct { 2328 n int 2329 } 2330 2331 func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) { 2332 ctr.n++ 2333 fmt.Fprintf(w, "counter = %d\n", ctr.n) 2334 } 2335 </pre> 2336 <p> 2337 (Keeping with our theme, note how <code>Fprintf</code> can print to an 2338 <code>http.ResponseWriter</code>.) 2339 For reference, here's how to attach such a server to a node on the URL tree. 2340 </p> 2341 <pre> 2342 import "net/http" 2343 ... 2344 ctr := new(Counter) 2345 http.Handle("/counter", ctr) 2346 </pre> 2347 <p> 2348 But why make <code>Counter</code> a struct? An integer is all that's needed. 2349 (The receiver needs to be a pointer so the increment is visible to the caller.) 2350 </p> 2351 <pre> 2352 // Simpler counter server. 2353 type Counter int 2354 2355 func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) { 2356 *ctr++ 2357 fmt.Fprintf(w, "counter = %d\n", *ctr) 2358 } 2359 </pre> 2360 <p> 2361 What if your program has some internal state that needs to be notified that a page 2362 has been visited? Tie a channel to the web page. 2363 </p> 2364 <pre> 2365 // A channel that sends a notification on each visit. 2366 // (Probably want the channel to be buffered.) 2367 type Chan chan *http.Request 2368 2369 func (ch Chan) ServeHTTP(w http.ResponseWriter, req *http.Request) { 2370 ch <- req 2371 fmt.Fprint(w, "notification sent") 2372 } 2373 </pre> 2374 <p> 2375 Finally, let's say we wanted to present on <code>/args</code> the arguments 2376 used when invoking the server binary. 2377 It's easy to write a function to print the arguments. 2378 </p> 2379 <pre> 2380 func ArgServer() { 2381 fmt.Println(os.Args) 2382 } 2383 </pre> 2384 <p> 2385 How do we turn that into an HTTP server? We could make <code>ArgServer</code> 2386 a method of some type whose value we ignore, but there's a cleaner way. 2387 Since we can define a method for any type except pointers and interfaces, 2388 we can write a method for a function. 2389 The <code>http</code> package contains this code: 2390 </p> 2391 <pre> 2392 // The HandlerFunc type is an adapter to allow the use of 2393 // ordinary functions as HTTP handlers. If f is a function 2394 // with the appropriate signature, HandlerFunc(f) is a 2395 // Handler object that calls f. 2396 type HandlerFunc func(ResponseWriter, *Request) 2397 2398 // ServeHTTP calls f(c, req). 2399 func (f HandlerFunc) ServeHTTP(w ResponseWriter, req *Request) { 2400 f(w, req) 2401 } 2402 </pre> 2403 <p> 2404 <code>HandlerFunc</code> is a type with a method, <code>ServeHTTP</code>, 2405 so values of that type can serve HTTP requests. Look at the implementation 2406 of the method: the receiver is a function, <code>f</code>, and the method 2407 calls <code>f</code>. That may seem odd but it's not that different from, say, 2408 the receiver being a channel and the method sending on the channel. 2409 </p> 2410 <p> 2411 To make <code>ArgServer</code> into an HTTP server, we first modify it 2412 to have the right signature. 2413 </p> 2414 <pre> 2415 // Argument server. 2416 func ArgServer(w http.ResponseWriter, req *http.Request) { 2417 fmt.Fprintln(w, os.Args) 2418 } 2419 </pre> 2420 <p> 2421 <code>ArgServer</code> now has same signature as <code>HandlerFunc</code>, 2422 so it can be converted to that type to access its methods, 2423 just as we converted <code>Sequence</code> to <code>IntSlice</code> 2424 to access <code>IntSlice.Sort</code>. 2425 The code to set it up is concise: 2426 </p> 2427 <pre> 2428 http.Handle("/args", http.HandlerFunc(ArgServer)) 2429 </pre> 2430 <p> 2431 When someone visits the page <code>/args</code>, 2432 the handler installed at that page has value <code>ArgServer</code> 2433 and type <code>HandlerFunc</code>. 2434 The HTTP server will invoke the method <code>ServeHTTP</code> 2435 of that type, with <code>ArgServer</code> as the receiver, which will in turn call 2436 <code>ArgServer</code> (via the invocation <code>f(c, req)</code> 2437 inside <code>HandlerFunc.ServeHTTP</code>). 2438 The arguments will then be displayed. 2439 </p> 2440 <p> 2441 In this section we have made an HTTP server from a struct, an integer, 2442 a channel, and a function, all because interfaces are just sets of 2443 methods, which can be defined for (almost) any type. 2444 </p> 2445 2446 <h2 id="blank">The blank identifier</h2> 2447 2448 <p> 2449 We've mentioned the blank identifier a couple of times now, in the context of 2450 <a href="#for"><code>for</code> <code>range</code> loops</a> 2451 and <a href="#maps">maps</a>. 2452 The blank identifier can be assigned or declared with any value of any type, with the 2453 value discarded harmlessly. 2454 It's a bit like writing to the Unix <code>/dev/null</code> file: 2455 it represents a write-only value 2456 to be used as a place-holder 2457 where a variable is needed but the actual value is irrelevant. 2458 It has uses beyond those we've seen already. 2459 </p> 2460 2461 <h3 id="blank_assign">The blank identifier in multiple assignment</h3> 2462 2463 <p> 2464 The use of a blank identifier in a <code>for</code> <code>range</code> loop is a 2465 special case of a general situation: multiple assignment. 2466 <p> 2467 If an assignment requires multiple values on the left side, 2468 but one of the values will not be used by the program, 2469 a blank identifier on the left-hand-side of 2470 the assignment avoids the need 2471 to create a dummy variable and makes it clear that the 2472 value is to be discarded. 2473 For instance, when calling a function that returns 2474 a value and an error, but only the error is important, 2475 use the blank identifier to discard the irrelevant value. 2476 </p> 2477 2478 <pre> 2479 if _, err := os.Stat(path); os.IsNotExist(err) { 2480 fmt.Printf("%s does not exist\n", path) 2481 } 2482 </pre> 2483 2484 <p> 2485 Occasionally you'll see code that discards the error value in order 2486 to ignore the error; this is terrible practice. Always check error returns; 2487 they're provided for a reason. 2488 </p> 2489 2490 <pre> 2491 // Bad! This code will crash if path does not exist. 2492 fi, _ := os.Stat(path) 2493 if fi.IsDir() { 2494 fmt.Printf("%s is a directory\n", path) 2495 } 2496 </pre> 2497 2498 <h3 id="blank_unused">Unused imports and variables</h3> 2499 2500 <p> 2501 It is an error to import a package or to declare a variable without using it. 2502 Unused imports bloat the program and slow compilation, 2503 while a variable that is initialized but not used is at least 2504 a wasted computation and perhaps indicative of a 2505 larger bug. 2506 When a program is under active development, however, 2507 unused imports and variables often arise and it can 2508 be annoying to delete them just to have the compilation proceed, 2509 only to have them be needed again later. 2510 The blank identifier provides a workaround. 2511 </p> 2512 <p> 2513 This half-written program has two unused imports 2514 (<code>fmt</code> and <code>io</code>) 2515 and an unused variable (<code>fd</code>), 2516 so it will not compile, but it would be nice to see if the 2517 code so far is correct. 2518 </p> 2519 {{code "/doc/progs/eff_unused1.go" `/package/` `$`}} 2520 <p> 2521 To silence complaints about the unused imports, use a 2522 blank identifier to refer to a symbol from the imported package. 2523 Similarly, assigning the unused variable <code>fd</code> 2524 to the blank identifier will silence the unused variable error. 2525 This version of the program does compile. 2526 </p> 2527 {{code "/doc/progs/eff_unused2.go" `/package/` `$`}} 2528 2529 <p> 2530 By convention, the global declarations to silence import errors 2531 should come right after the imports and be commented, 2532 both to make them easy to find and as a reminder to clean things up later. 2533 </p> 2534 2535 <h3 id="blank_import">Import for side effect</h3> 2536 2537 <p> 2538 An unused import like <code>fmt</code> or <code>io</code> in the 2539 previous example should eventually be used or removed: 2540 blank assignments identify code as a work in progress. 2541 But sometimes it is useful to import a package only for its 2542 side effects, without any explicit use. 2543 For example, during its <code>init</code> function, 2544 the <code><a href="/pkg/net/http/pprof/">net/http/pprof</a></code> 2545 package registers HTTP handlers that provide 2546 debugging information. It has an exported API, but 2547 most clients need only the handler registration and 2548 access the data through a web page. 2549 To import the package only for its side effects, rename the package 2550 to the blank identifier: 2551 </p> 2552 <pre> 2553 import _ "net/http/pprof" 2554 </pre> 2555 <p> 2556 This form of import makes clear that the package is being 2557 imported for its side effects, because there is no other possible 2558 use of the package: in this file, it doesn't have a name. 2559 (If it did, and we didn't use that name, the compiler would reject the program.) 2560 </p> 2561 2562 <h3 id="blank_implements">Interface checks</h3> 2563 2564 <p> 2565 As we saw in the discussion of <a href="#interfaces_and_types">interfaces</a> above, 2566 a type need not declare explicitly that it implements an interface. 2567 Instead, a type implements the interface just by implementing the interface's methods. 2568 In practice, most interface conversions are static and therefore checked at compile time. 2569 For example, passing an <code>*os.File</code> to a function 2570 expecting an <code>io.Reader</code> will not compile unless 2571 <code>*os.File</code> implements the <code>io.Reader</code> interface. 2572 </p> 2573 2574 <p> 2575 Some interface checks do happen at run-time, though. 2576 One instance is in the <code><a href="/pkg/encoding/json/">encoding/json</a></code> 2577 package, which defines a <code><a href="/pkg/encoding/json/#Marshaler">Marshaler</a></code> 2578 interface. When the JSON encoder receives a value that implements that interface, 2579 the encoder invokes the value's marshaling method to convert it to JSON 2580 instead of doing the standard conversion. 2581 The encoder checks this property at run time with a <a href="#interface_conversions">type assertion</a> like: 2582 </p> 2583 2584 <pre> 2585 m, ok := val.(json.Marshaler) 2586 </pre> 2587 2588 <p> 2589 If it's necessary only to ask whether a type implements an interface, without 2590 actually using the interface itself, perhaps as part of an error check, use the blank 2591 identifier to ignore the type-asserted value: 2592 </p> 2593 2594 <pre> 2595 if _, ok := val.(json.Marshaler); ok { 2596 fmt.Printf("value %v of type %T implements json.Marshaler\n", val, val) 2597 } 2598 </pre> 2599 2600 <p> 2601 One place this situation arises is when it is necessary to guarantee within the package implementing the type that 2602 it actually satisfies the interface. 2603 If a type—for example, 2604 <code><a href="/pkg/encoding/json/#RawMessage">json.RawMessage</a></code>—needs 2605 a custom JSON representation, it should implement 2606 <code>json.Marshaler</code>, but there are no static conversions that would 2607 cause the compiler to verify this automatically. 2608 If the type inadvertently fails to satisfy the interface, the JSON encoder will still work, 2609 but will not use the custom implementation. 2610 To guarantee that the implementation is correct, 2611 a global declaration using the blank identifier can be used in the package: 2612 </p> 2613 <pre> 2614 var _ json.Marshaler = (*RawMessage)(nil) 2615 </pre> 2616 <p> 2617 In this declaration, the assignment involving a conversion of a 2618 <code>*RawMessage</code> to a <code>Marshaler</code> 2619 requires that <code>*RawMessage</code> implements <code>Marshaler</code>, 2620 and that property will be checked at compile time. 2621 Should the <code>json.Marshaler</code> interface change, this package 2622 will no longer compile and we will be on notice that it needs to be updated. 2623 </p> 2624 2625 <p> 2626 The appearance of the blank identifier in this construct indicates that 2627 the declaration exists only for the type checking, 2628 not to create a variable. 2629 Don't do this for every type that satisfies an interface, though. 2630 By convention, such declarations are only used 2631 when there are no static conversions already present in the code, 2632 which is a rare event. 2633 </p> 2634 2635 2636 <h2 id="embedding">Embedding</h2> 2637 2638 <p> 2639 Go does not provide the typical, type-driven notion of subclassing, 2640 but it does have the ability to “borrow” pieces of an 2641 implementation by <em>embedding</em> types within a struct or 2642 interface. 2643 </p> 2644 <p> 2645 Interface embedding is very simple. 2646 We've mentioned the <code>io.Reader</code> and <code>io.Writer</code> interfaces before; 2647 here are their definitions. 2648 </p> 2649 <pre> 2650 type Reader interface { 2651 Read(p []byte) (n int, err error) 2652 } 2653 2654 type Writer interface { 2655 Write(p []byte) (n int, err error) 2656 } 2657 </pre> 2658 <p> 2659 The <code>io</code> package also exports several other interfaces 2660 that specify objects that can implement several such methods. 2661 For instance, there is <code>io.ReadWriter</code>, an interface 2662 containing both <code>Read</code> and <code>Write</code>. 2663 We could specify <code>io.ReadWriter</code> by listing the 2664 two methods explicitly, but it's easier and more evocative 2665 to embed the two interfaces to form the new one, like this: 2666 </p> 2667 <pre> 2668 // ReadWriter is the interface that combines the Reader and Writer interfaces. 2669 type ReadWriter interface { 2670 Reader 2671 Writer 2672 } 2673 </pre> 2674 <p> 2675 This says just what it looks like: A <code>ReadWriter</code> can do 2676 what a <code>Reader</code> does <em>and</em> what a <code>Writer</code> 2677 does; it is a union of the embedded interfaces (which must be disjoint 2678 sets of methods). 2679 Only interfaces can be embedded within interfaces. 2680 </p> 2681 <p> 2682 The same basic idea applies to structs, but with more far-reaching 2683 implications. The <code>bufio</code> package has two struct types, 2684 <code>bufio.Reader</code> and <code>bufio.Writer</code>, each of 2685 which of course implements the analogous interfaces from package 2686 <code>io</code>. 2687 And <code>bufio</code> also implements a buffered reader/writer, 2688 which it does by combining a reader and a writer into one struct 2689 using embedding: it lists the types within the struct 2690 but does not give them field names. 2691 </p> 2692 <pre> 2693 // ReadWriter stores pointers to a Reader and a Writer. 2694 // It implements io.ReadWriter. 2695 type ReadWriter struct { 2696 *Reader // *bufio.Reader 2697 *Writer // *bufio.Writer 2698 } 2699 </pre> 2700 <p> 2701 The embedded elements are pointers to structs and of course 2702 must be initialized to point to valid structs before they 2703 can be used. 2704 The <code>ReadWriter</code> struct could be written as 2705 </p> 2706 <pre> 2707 type ReadWriter struct { 2708 reader *Reader 2709 writer *Writer 2710 } 2711 </pre> 2712 <p> 2713 but then to promote the methods of the fields and to 2714 satisfy the <code>io</code> interfaces, we would also need 2715 to provide forwarding methods, like this: 2716 </p> 2717 <pre> 2718 func (rw *ReadWriter) Read(p []byte) (n int, err error) { 2719 return rw.reader.Read(p) 2720 } 2721 </pre> 2722 <p> 2723 By embedding the structs directly, we avoid this bookkeeping. 2724 The methods of embedded types come along for free, which means that <code>bufio.ReadWriter</code> 2725 not only has the methods of <code>bufio.Reader</code> and <code>bufio.Writer</code>, 2726 it also satisfies all three interfaces: 2727 <code>io.Reader</code>, 2728 <code>io.Writer</code>, and 2729 <code>io.ReadWriter</code>. 2730 </p> 2731 <p> 2732 There's an important way in which embedding differs from subclassing. When we embed a type, 2733 the methods of that type become methods of the outer type, 2734 but when they are invoked the receiver of the method is the inner type, not the outer one. 2735 In our example, when the <code>Read</code> method of a <code>bufio.ReadWriter</code> is 2736 invoked, it has exactly the same effect as the forwarding method written out above; 2737 the receiver is the <code>reader</code> field of the <code>ReadWriter</code>, not the 2738 <code>ReadWriter</code> itself. 2739 </p> 2740 <p> 2741 Embedding can also be a simple convenience. 2742 This example shows an embedded field alongside a regular, named field. 2743 </p> 2744 <pre> 2745 type Job struct { 2746 Command string 2747 *log.Logger 2748 } 2749 </pre> 2750 <p> 2751 The <code>Job</code> type now has the <code>Log</code>, <code>Logf</code> 2752 and other 2753 methods of <code>*log.Logger</code>. We could have given the <code>Logger</code> 2754 a field name, of course, but it's not necessary to do so. And now, once 2755 initialized, we can 2756 log to the <code>Job</code>: 2757 </p> 2758 <pre> 2759 job.Log("starting now...") 2760 </pre> 2761 <p> 2762 The <code>Logger</code> is a regular field of the <code>Job</code> struct, 2763 so we can initialize it in the usual way inside the constructor for <code>Job</code>, like this, 2764 </p> 2765 <pre> 2766 func NewJob(command string, logger *log.Logger) *Job { 2767 return &Job{command, logger} 2768 } 2769 </pre> 2770 <p> 2771 or with a composite literal, 2772 </p> 2773 <pre> 2774 job := &Job{command, log.New(os.Stderr, "Job: ", log.Ldate)} 2775 </pre> 2776 <p> 2777 If we need to refer to an embedded field directly, the type name of the field, 2778 ignoring the package qualifier, serves as a field name, as it did 2779 in the <code>Read</code> method of our <code>ReaderWriter</code> struct. 2780 Here, if we needed to access the 2781 <code>*log.Logger</code> of a <code>Job</code> variable <code>job</code>, 2782 we would write <code>job.Logger</code>, 2783 which would be useful if we wanted to refine the methods of <code>Logger</code>. 2784 </p> 2785 <pre> 2786 func (job *Job) Logf(format string, args ...interface{}) { 2787 job.Logger.Logf("%q: %s", job.Command, fmt.Sprintf(format, args...)) 2788 } 2789 </pre> 2790 <p> 2791 Embedding types introduces the problem of name conflicts but the rules to resolve 2792 them are simple. 2793 First, a field or method <code>X</code> hides any other item <code>X</code> in a more deeply 2794 nested part of the type. 2795 If <code>log.Logger</code> contained a field or method called <code>Command</code>, the <code>Command</code> field 2796 of <code>Job</code> would dominate it. 2797 </p> 2798 <p> 2799 Second, if the same name appears at the same nesting level, it is usually an error; 2800 it would be erroneous to embed <code>log.Logger</code> if the <code>Job</code> struct 2801 contained another field or method called <code>Logger</code>. 2802 However, if the duplicate name is never mentioned in the program outside the type definition, it is OK. 2803 This qualification provides some protection against changes made to types embedded from outside; there 2804 is no problem if a field is added that conflicts with another field in another subtype if neither field 2805 is ever used. 2806 </p> 2807 2808 2809 <h2 id="concurrency">Concurrency</h2> 2810 2811 <h3 id="sharing">Share by communicating</h3> 2812 2813 <p> 2814 Concurrent programming is a large topic and there is space only for some 2815 Go-specific highlights here. 2816 </p> 2817 <p> 2818 Concurrent programming in many environments is made difficult by the 2819 subtleties required to implement correct access to shared variables. Go encourages 2820 a different approach in which shared values are passed around on channels 2821 and, in fact, never actively shared by separate threads of execution. 2822 Only one goroutine has access to the value at any given time. 2823 Data races cannot occur, by design. 2824 To encourage this way of thinking we have reduced it to a slogan: 2825 </p> 2826 <blockquote> 2827 Do not communicate by sharing memory; 2828 instead, share memory by communicating. 2829 </blockquote> 2830 <p> 2831 This approach can be taken too far. Reference counts may be best done 2832 by putting a mutex around an integer variable, for instance. But as a 2833 high-level approach, using channels to control access makes it easier 2834 to write clear, correct programs. 2835 </p> 2836 <p> 2837 One way to think about this model is to consider a typical single-threaded 2838 program running on one CPU. It has no need for synchronization primitives. 2839 Now run another such instance; it too needs no synchronization. Now let those 2840 two communicate; if the communication is the synchronizer, there's still no need 2841 for other synchronization. Unix pipelines, for example, fit this model 2842 perfectly. Although Go's approach to concurrency originates in Hoare's 2843 Communicating Sequential Processes (CSP), 2844 it can also be seen as a type-safe generalization of Unix pipes. 2845 </p> 2846 2847 <h3 id="goroutines">Goroutines</h3> 2848 2849 <p> 2850 They're called <em>goroutines</em> because the existing 2851 terms—threads, coroutines, processes, and so on—convey 2852 inaccurate connotations. A goroutine has a simple model: it is a 2853 function executing concurrently with other goroutines in the same 2854 address space. It is lightweight, costing little more than the 2855 allocation of stack space. 2856 And the stacks start small, so they are cheap, and grow 2857 by allocating (and freeing) heap storage as required. 2858 </p> 2859 <p> 2860 Goroutines are multiplexed onto multiple OS threads so if one should 2861 block, such as while waiting for I/O, others continue to run. Their 2862 design hides many of the complexities of thread creation and 2863 management. 2864 </p> 2865 <p> 2866 Prefix a function or method call with the <code>go</code> 2867 keyword to run the call in a new goroutine. 2868 When the call completes, the goroutine 2869 exits, silently. (The effect is similar to the Unix shell's 2870 <code>&</code> notation for running a command in the 2871 background.) 2872 </p> 2873 <pre> 2874 go list.Sort() // run list.Sort concurrently; don't wait for it. 2875 </pre> 2876 <p> 2877 A function literal can be handy in a goroutine invocation. 2878 </p> 2879 <pre> 2880 func Announce(message string, delay time.Duration) { 2881 go func() { 2882 time.Sleep(delay) 2883 fmt.Println(message) 2884 }() // Note the parentheses - must call the function. 2885 } 2886 </pre> 2887 <p> 2888 In Go, function literals are closures: the implementation makes 2889 sure the variables referred to by the function survive as long as they are active. 2890 </p> 2891 <p> 2892 These examples aren't too practical because the functions have no way of signaling 2893 completion. For that, we need channels. 2894 </p> 2895 2896 <h3 id="channels">Channels</h3> 2897 2898 <p> 2899 Like maps, channels are allocated with <code>make</code>, and 2900 the resulting value acts as a reference to an underlying data structure. 2901 If an optional integer parameter is provided, it sets the buffer size for the channel. 2902 The default is zero, for an unbuffered or synchronous channel. 2903 </p> 2904 <pre> 2905 ci := make(chan int) // unbuffered channel of integers 2906 cj := make(chan int, 0) // unbuffered channel of integers 2907 cs := make(chan *os.File, 100) // buffered channel of pointers to Files 2908 </pre> 2909 <p> 2910 Unbuffered channels combine communication—the exchange of a value—with 2911 synchronization—guaranteeing that two calculations (goroutines) are in 2912 a known state. 2913 </p> 2914 <p> 2915 There are lots of nice idioms using channels. Here's one to get us started. 2916 In the previous section we launched a sort in the background. A channel 2917 can allow the launching goroutine to wait for the sort to complete. 2918 </p> 2919 <pre> 2920 c := make(chan int) // Allocate a channel. 2921 // Start the sort in a goroutine; when it completes, signal on the channel. 2922 go func() { 2923 list.Sort() 2924 c <- 1 // Send a signal; value does not matter. 2925 }() 2926 doSomethingForAWhile() 2927 <-c // Wait for sort to finish; discard sent value. 2928 </pre> 2929 <p> 2930 Receivers always block until there is data to receive. 2931 If the channel is unbuffered, the sender blocks until the receiver has 2932 received the value. 2933 If the channel has a buffer, the sender blocks only until the 2934 value has been copied to the buffer; if the buffer is full, this 2935 means waiting until some receiver has retrieved a value. 2936 </p> 2937 <p> 2938 A buffered channel can be used like a semaphore, for instance to 2939 limit throughput. In this example, incoming requests are passed 2940 to <code>handle</code>, which receives a value from the channel, processes 2941 the request, and then sends a value back to the channel 2942 to ready the "semaphore" for the next consumer. 2943 The capacity of the channel buffer limits the number of 2944 simultaneous calls to <code>process</code>, 2945 so during initialization we prime the channel by filling it to capacity. 2946 </p> 2947 <pre> 2948 var sem = make(chan int, MaxOutstanding) 2949 2950 func handle(r *Request) { 2951 <-sem // Wait for active queue to drain. 2952 process(r) // May take a long time. 2953 sem <- 1 // Done; enable next request to run. 2954 } 2955 2956 func init() { 2957 for i := 0; i < MaxOutstanding; i++ { 2958 sem <- 1 2959 } 2960 } 2961 2962 func Serve(queue chan *Request) { 2963 for { 2964 req := <-queue 2965 go handle(req) // Don't wait for handle to finish. 2966 } 2967 } 2968 </pre> 2969 2970 <p> 2971 Because data synchronization occurs on a receive from a channel 2972 (that is, the send "happens before" the receive; see 2973 <a href="/ref/mem">The Go Memory Model</a>), 2974 acquisition of the semaphore must be on a channel receive, not a send. 2975 </p> 2976 2977 <p> 2978 This design has a problem, though: <code>Serve</code> 2979 creates a new goroutine for 2980 every incoming request, even though only <code>MaxOutstanding</code> 2981 of them can run at any moment. 2982 As a result, the program can consume unlimited resources if the requests come in too fast. 2983 We can address that deficiency by changing <code>Serve</code> to 2984 gate the creation of the goroutines. 2985 Here's an obvious solution, but beware it has a bug we'll fix subsequently: 2986 </p> 2987 2988 <pre> 2989 func Serve(queue chan *Request) { 2990 for req := range queue { 2991 <-sem 2992 go func() { 2993 process(req) // Buggy; see explanation below. 2994 sem <- 1 2995 }() 2996 } 2997 }</pre> 2998 2999 <p> 3000 The bug is that in a Go <code>for</code> loop, the loop variable 3001 is reused for each iteration, so the <code>req</code> 3002 variable is shared across all goroutines. 3003 That's not what we want. 3004 We need to make sure that <code>req</code> is unique for each goroutine. 3005 Here's one way to do that, passing the value of <code>req</code> as an argument 3006 to the closure in the goroutine: 3007 </p> 3008 3009 <pre> 3010 func Serve(queue chan *Request) { 3011 for req := range queue { 3012 <-sem 3013 go func(req *Request) { 3014 process(req) 3015 sem <- 1 3016 }(req) 3017 } 3018 }</pre> 3019 3020 <p> 3021 Compare this version with the previous to see the difference in how 3022 the closure is declared and run. 3023 Another solution is just to create a new variable with the same 3024 name, as in this example: 3025 </p> 3026 3027 <pre> 3028 func Serve(queue chan *Request) { 3029 for req := range queue { 3030 <-sem 3031 req := req // Create new instance of req for the goroutine. 3032 go func() { 3033 process(req) 3034 sem <- 1 3035 }() 3036 } 3037 }</pre> 3038 3039 <p> 3040 It may seem odd to write 3041 </p> 3042 3043 <pre> 3044 req := req 3045 </pre> 3046 3047 <p> 3048 but it's a legal and idiomatic in Go to do this. 3049 You get a fresh version of the variable with the same name, deliberately 3050 shadowing the loop variable locally but unique to each goroutine. 3051 </p> 3052 3053 <p> 3054 Going back to the general problem of writing the server, 3055 another approach that manages resources well is to start a fixed 3056 number of <code>handle</code> goroutines all reading from the request 3057 channel. 3058 The number of goroutines limits the number of simultaneous 3059 calls to <code>process</code>. 3060 This <code>Serve</code> function also accepts a channel on which 3061 it will be told to exit; after launching the goroutines it blocks 3062 receiving from that channel. 3063 </p> 3064 3065 <pre> 3066 func handle(queue chan *Request) { 3067 for r := range queue { 3068 process(r) 3069 } 3070 } 3071 3072 func Serve(clientRequests chan *Request, quit chan bool) { 3073 // Start handlers 3074 for i := 0; i < MaxOutstanding; i++ { 3075 go handle(clientRequests) 3076 } 3077 <-quit // Wait to be told to exit. 3078 } 3079 </pre> 3080 3081 <h3 id="chan_of_chan">Channels of channels</h3> 3082 <p> 3083 One of the most important properties of Go is that 3084 a channel is a first-class value that can be allocated and passed 3085 around like any other. A common use of this property is 3086 to implement safe, parallel demultiplexing. 3087 </p> 3088 <p> 3089 In the example in the previous section, <code>handle</code> was 3090 an idealized handler for a request but we didn't define the 3091 type it was handling. If that type includes a channel on which 3092 to reply, each client can provide its own path for the answer. 3093 Here's a schematic definition of type <code>Request</code>. 3094 </p> 3095 <pre> 3096 type Request struct { 3097 args []int 3098 f func([]int) int 3099 resultChan chan int 3100 } 3101 </pre> 3102 <p> 3103 The client provides a function and its arguments, as well as 3104 a channel inside the request object on which to receive the answer. 3105 </p> 3106 <pre> 3107 func sum(a []int) (s int) { 3108 for _, v := range a { 3109 s += v 3110 } 3111 return 3112 } 3113 3114 request := &Request{[]int{3, 4, 5}, sum, make(chan int)} 3115 // Send request 3116 clientRequests <- request 3117 // Wait for response. 3118 fmt.Printf("answer: %d\n", <-request.resultChan) 3119 </pre> 3120 <p> 3121 On the server side, the handler function is the only thing that changes. 3122 </p> 3123 <pre> 3124 func handle(queue chan *Request) { 3125 for req := range queue { 3126 req.resultChan <- req.f(req.args) 3127 } 3128 } 3129 </pre> 3130 <p> 3131 There's clearly a lot more to do to make it realistic, but this 3132 code is a framework for a rate-limited, parallel, non-blocking RPC 3133 system, and there's not a mutex in sight. 3134 </p> 3135 3136 <h3 id="parallel">Parallelization</h3> 3137 <p> 3138 Another application of these ideas is to parallelize a calculation 3139 across multiple CPU cores. If the calculation can be broken into 3140 separate pieces that can execute independently, it can be parallelized, 3141 with a channel to signal when each piece completes. 3142 </p> 3143 <p> 3144 Let's say we have an expensive operation to perform on a vector of items, 3145 and that the value of the operation on each item is independent, 3146 as in this idealized example. 3147 </p> 3148 <pre> 3149 type Vector []float64 3150 3151 // Apply the operation to v[i], v[i+1] ... up to v[n-1]. 3152 func (v Vector) DoSome(i, n int, u Vector, c chan int) { 3153 for ; i < n; i++ { 3154 v[i] += u.Op(v[i]) 3155 } 3156 c <- 1 // signal that this piece is done 3157 } 3158 </pre> 3159 <p> 3160 We launch the pieces independently in a loop, one per CPU. 3161 They can complete in any order but it doesn't matter; we just 3162 count the completion signals by draining the channel after 3163 launching all the goroutines. 3164 </p> 3165 <pre> 3166 const NCPU = 4 // number of CPU cores 3167 3168 func (v Vector) DoAll(u Vector) { 3169 c := make(chan int, NCPU) // Buffering optional but sensible. 3170 for i := 0; i < NCPU; i++ { 3171 go v.DoSome(i*len(v)/NCPU, (i+1)*len(v)/NCPU, u, c) 3172 } 3173 // Drain the channel. 3174 for i := 0; i < NCPU; i++ { 3175 <-c // wait for one task to complete 3176 } 3177 // All done. 3178 } 3179 3180 </pre> 3181 3182 <p> 3183 The current implementation of the Go runtime 3184 will not parallelize this code by default. 3185 It dedicates only a single core to user-level processing. An 3186 arbitrary number of goroutines can be blocked in system calls, but 3187 by default only one can be executing user-level code at any time. 3188 It should be smarter and one day it will be smarter, but until it 3189 is if you want CPU parallelism you must tell the run-time 3190 how many goroutines you want executing code simultaneously. There 3191 are two related ways to do this. Either run your job with environment 3192 variable <code>GOMAXPROCS</code> set to the number of cores to use 3193 or import the <code>runtime</code> package and call 3194 <code>runtime.GOMAXPROCS(NCPU)</code>. 3195 A helpful value might be <code>runtime.NumCPU()</code>, which reports the number 3196 of logical CPUs on the local machine. 3197 Again, this requirement is expected to be retired as the scheduling and run-time improve. 3198 </p> 3199 3200 <p> 3201 Be sure not to confuse the ideas of concurrency—structuring a program 3202 as independently executing components—and parallelism—executing 3203 calculations in parallel for efficiency on multiple CPUs. 3204 Although the concurrency features of Go can make some problems easy 3205 to structure as parallel computations, Go is a concurrent language, 3206 not a parallel one, and not all parallelization problems fit Go's model. 3207 For a discussion of the distinction, see the talk cited in 3208 <a href="http://blog.golang.org/2013/01/concurrency-is-not-parallelism.html">this 3209 blog post</a>. 3210 3211 <h3 id="leaky_buffer">A leaky buffer</h3> 3212 3213 <p> 3214 The tools of concurrent programming can even make non-concurrent 3215 ideas easier to express. Here's an example abstracted from an RPC 3216 package. The client goroutine loops receiving data from some source, 3217 perhaps a network. To avoid allocating and freeing buffers, it keeps 3218 a free list, and uses a buffered channel to represent it. If the 3219 channel is empty, a new buffer gets allocated. 3220 Once the message buffer is ready, it's sent to the server on 3221 <code>serverChan</code>. 3222 </p> 3223 <pre> 3224 var freeList = make(chan *Buffer, 100) 3225 var serverChan = make(chan *Buffer) 3226 3227 func client() { 3228 for { 3229 var b *Buffer 3230 // Grab a buffer if available; allocate if not. 3231 select { 3232 case b = <-freeList: 3233 // Got one; nothing more to do. 3234 default: 3235 // None free, so allocate a new one. 3236 b = new(Buffer) 3237 } 3238 load(b) // Read next message from the net. 3239 serverChan <- b // Send to server. 3240 } 3241 } 3242 </pre> 3243 <p> 3244 The server loop receives each message from the client, processes it, 3245 and returns the buffer to the free list. 3246 </p> 3247 <pre> 3248 func server() { 3249 for { 3250 b := <-serverChan // Wait for work. 3251 process(b) 3252 // Reuse buffer if there's room. 3253 select { 3254 case freeList <- b: 3255 // Buffer on free list; nothing more to do. 3256 default: 3257 // Free list full, just carry on. 3258 } 3259 } 3260 } 3261 </pre> 3262 <p> 3263 The client attempts to retrieve a buffer from <code>freeList</code>; 3264 if none is available, it allocates a fresh one. 3265 The server's send to <code>freeList</code> puts <code>b</code> back 3266 on the free list unless the list is full, in which case the 3267 buffer is dropped on the floor to be reclaimed by 3268 the garbage collector. 3269 (The <code>default</code> clauses in the <code>select</code> 3270 statements execute when no other case is ready, 3271 meaning that the <code>selects</code> never block.) 3272 This implementation builds a leaky bucket free list 3273 in just a few lines, relying on the buffered channel and 3274 the garbage collector for bookkeeping. 3275 </p> 3276 3277 <h2 id="errors">Errors</h2> 3278 3279 <p> 3280 Library routines must often return some sort of error indication to 3281 the caller. As mentioned earlier, Go's multivalue return makes it 3282 easy to return a detailed error description alongside the normal 3283 return value. By convention, errors have type <code>error</code>, 3284 a simple built-in interface. 3285 </p> 3286 <pre> 3287 type error interface { 3288 Error() string 3289 } 3290 </pre> 3291 <p> 3292 A library writer is free to implement this interface with a 3293 richer model under the covers, making it possible not only 3294 to see the error but also to provide some context. 3295 For example, <code>os.Open</code> returns an <code>os.PathError</code>. 3296 </p> 3297 <pre> 3298 // PathError records an error and the operation and 3299 // file path that caused it. 3300 type PathError struct { 3301 Op string // "open", "unlink", etc. 3302 Path string // The associated file. 3303 Err error // Returned by the system call. 3304 } 3305 3306 func (e *PathError) Error() string { 3307 return e.Op + " " + e.Path + ": " + e.Err.Error() 3308 } 3309 </pre> 3310 <p> 3311 <code>PathError</code>'s <code>Error</code> generates 3312 a string like this: 3313 </p> 3314 <pre> 3315 open /etc/passwx: no such file or directory 3316 </pre> 3317 <p> 3318 Such an error, which includes the problematic file name, the 3319 operation, and the operating system error it triggered, is useful even 3320 if printed far from the call that caused it; 3321 it is much more informative than the plain 3322 "no such file or directory". 3323 </p> 3324 3325 <p> 3326 When feasible, error strings should identify their origin, such as by having 3327 a prefix naming the operation or package that generated the error. For example, in package 3328 <code>image</code>, the string representation for a decoding error due to an 3329 unknown format is "image: unknown format". 3330 </p> 3331 3332 <p> 3333 Callers that care about the precise error details can 3334 use a type switch or a type assertion to look for specific 3335 errors and extract details. For <code>PathErrors</code> 3336 this might include examining the internal <code>Err</code> 3337 field for recoverable failures. 3338 </p> 3339 3340 <pre> 3341 for try := 0; try < 2; try++ { 3342 file, err = os.Create(filename) 3343 if err == nil { 3344 return 3345 } 3346 if e, ok := err.(*os.PathError); ok && e.Err == syscall.ENOSPC { 3347 deleteTempFiles() // Recover some space. 3348 continue 3349 } 3350 return 3351 } 3352 </pre> 3353 3354 <p> 3355 The second <code>if</code> statement here is another <a href="#interface_conversions">type assertion</a>. 3356 If it fails, <code>ok</code> will be false, and <code>e</code> 3357 will be <code>nil</code>. 3358 If it succeeds, <code>ok</code> will be true, which means the 3359 error was of type <code>*os.PathError</code>, and then so is <code>e</code>, 3360 which we can examine for more information about the error. 3361 </p> 3362 3363 <h3 id="panic">Panic</h3> 3364 3365 <p> 3366 The usual way to report an error to a caller is to return an 3367 <code>error</code> as an extra return value. The canonical 3368 <code>Read</code> method is a well-known instance; it returns a byte 3369 count and an <code>error</code>. But what if the error is 3370 unrecoverable? Sometimes the program simply cannot continue. 3371 </p> 3372 3373 <p> 3374 For this purpose, there is a built-in function <code>panic</code> 3375 that in effect creates a run-time error that will stop the program 3376 (but see the next section). The function takes a single argument 3377 of arbitrary type—often a string—to be printed as the 3378 program dies. It's also a way to indicate that something impossible has 3379 happened, such as exiting an infinite loop. 3380 </p> 3381 3382 3383 <pre> 3384 // A toy implementation of cube root using Newton's method. 3385 func CubeRoot(x float64) float64 { 3386 z := x/3 // Arbitrary initial value 3387 for i := 0; i < 1e6; i++ { 3388 prevz := z 3389 z -= (z*z*z-x) / (3*z*z) 3390 if veryClose(z, prevz) { 3391 return z 3392 } 3393 } 3394 // A million iterations has not converged; something is wrong. 3395 panic(fmt.Sprintf("CubeRoot(%g) did not converge", x)) 3396 } 3397 </pre> 3398 3399 <p> 3400 This is only an example but real library functions should 3401 avoid <code>panic</code>. If the problem can be masked or worked 3402 around, it's always better to let things continue to run rather 3403 than taking down the whole program. One possible counterexample 3404 is during initialization: if the library truly cannot set itself up, 3405 it might be reasonable to panic, so to speak. 3406 </p> 3407 3408 <pre> 3409 var user = os.Getenv("USER") 3410 3411 func init() { 3412 if user == "" { 3413 panic("no value for $USER") 3414 } 3415 } 3416 </pre> 3417 3418 <h3 id="recover">Recover</h3> 3419 3420 <p> 3421 When <code>panic</code> is called, including implicitly for run-time 3422 errors such as indexing a slice out of bounds or failing a type 3423 assertion, it immediately stops execution of the current function 3424 and begins unwinding the stack of the goroutine, running any deferred 3425 functions along the way. If that unwinding reaches the top of the 3426 goroutine's stack, the program dies. However, it is possible to 3427 use the built-in function <code>recover</code> to regain control 3428 of the goroutine and resume normal execution. 3429 </p> 3430 3431 <p> 3432 A call to <code>recover</code> stops the unwinding and returns the 3433 argument passed to <code>panic</code>. Because the only code that 3434 runs while unwinding is inside deferred functions, <code>recover</code> 3435 is only useful inside deferred functions. 3436 </p> 3437 3438 <p> 3439 One application of <code>recover</code> is to shut down a failing goroutine 3440 inside a server without killing the other executing goroutines. 3441 </p> 3442 3443 <pre> 3444 func server(workChan <-chan *Work) { 3445 for work := range workChan { 3446 go safelyDo(work) 3447 } 3448 } 3449 3450 func safelyDo(work *Work) { 3451 defer func() { 3452 if err := recover(); err != nil { 3453 log.Println("work failed:", err) 3454 } 3455 }() 3456 do(work) 3457 } 3458 </pre> 3459 3460 <p> 3461 In this example, if <code>do(work)</code> panics, the result will be 3462 logged and the goroutine will exit cleanly without disturbing the 3463 others. There's no need to do anything else in the deferred closure; 3464 calling <code>recover</code> handles the condition completely. 3465 </p> 3466 3467 <p> 3468 Because <code>recover</code> always returns <code>nil</code> unless called directly 3469 from a deferred function, deferred code can call library routines that themselves 3470 use <code>panic</code> and <code>recover</code> without failing. As an example, 3471 the deferred function in <code>safelyDo</code> might call a logging function before 3472 calling <code>recover</code>, and that logging code would run unaffected 3473 by the panicking state. 3474 </p> 3475 3476 <p> 3477 With our recovery pattern in place, the <code>do</code> 3478 function (and anything it calls) can get out of any bad situation 3479 cleanly by calling <code>panic</code>. We can use that idea to 3480 simplify error handling in complex software. Let's look at an 3481 idealized version of a <code>regexp</code> package, which reports 3482 parsing errors by calling <code>panic</code> with a local 3483 error type. Here's the definition of <code>Error</code>, 3484 an <code>error</code> method, and the <code>Compile</code> function. 3485 </p> 3486 3487 <pre> 3488 // Error is the type of a parse error; it satisfies the error interface. 3489 type Error string 3490 func (e Error) Error() string { 3491 return string(e) 3492 } 3493 3494 // error is a method of *Regexp that reports parsing errors by 3495 // panicking with an Error. 3496 func (regexp *Regexp) error(err string) { 3497 panic(Error(err)) 3498 } 3499 3500 // Compile returns a parsed representation of the regular expression. 3501 func Compile(str string) (regexp *Regexp, err error) { 3502 regexp = new(Regexp) 3503 // doParse will panic if there is a parse error. 3504 defer func() { 3505 if e := recover(); e != nil { 3506 regexp = nil // Clear return value. 3507 err = e.(Error) // Will re-panic if not a parse error. 3508 } 3509 }() 3510 return regexp.doParse(str), nil 3511 } 3512 </pre> 3513 3514 <p> 3515 If <code>doParse</code> panics, the recovery block will set the 3516 return value to <code>nil</code>—deferred functions can modify 3517 named return values. It will then check, in the assignment 3518 to <code>err</code>, that the problem was a parse error by asserting 3519 that it has the local type <code>Error</code>. 3520 If it does not, the type assertion will fail, causing a run-time error 3521 that continues the stack unwinding as though nothing had interrupted 3522 it. 3523 This check means that if something unexpected happens, such 3524 as an index out of bounds, the code will fail even though we 3525 are using <code>panic</code> and <code>recover</code> to handle 3526 parse errors. 3527 </p> 3528 3529 <p> 3530 With error handling in place, the <code>error</code> method (because it's a 3531 method bound to a type, it's fine, even natural, for it to have the same name 3532 as the builtin <code>error</code> type) 3533 makes it easy to report parse errors without worrying about unwinding 3534 the parse stack by hand: 3535 </p> 3536 3537 <pre> 3538 if pos == 0 { 3539 re.error("'*' illegal at start of expression") 3540 } 3541 </pre> 3542 3543 <p> 3544 Useful though this pattern is, it should be used only within a package. 3545 <code>Parse</code> turns its internal <code>panic</code> calls into 3546 <code>error</code> values; it does not expose <code>panics</code> 3547 to its client. That is a good rule to follow. 3548 </p> 3549 3550 <p> 3551 By the way, this re-panic idiom changes the panic value if an actual 3552 error occurs. However, both the original and new failures will be 3553 presented in the crash report, so the root cause of the problem will 3554 still be visible. Thus this simple re-panic approach is usually 3555 sufficient—it's a crash after all—but if you want to 3556 display only the original value, you can write a little more code to 3557 filter unexpected problems and re-panic with the original error. 3558 That's left as an exercise for the reader. 3559 </p> 3560 3561 3562 <h2 id="web_server">A web server</h2> 3563 3564 <p> 3565 Let's finish with a complete Go program, a web server. 3566 This one is actually a kind of web re-server. 3567 Google provides a service at 3568 <a href="http://chart.apis.google.com">http://chart.apis.google.com</a> 3569 that does automatic formatting of data into charts and graphs. 3570 It's hard to use interactively, though, 3571 because you need to put the data into the URL as a query. 3572 The program here provides a nicer interface to one form of data: given a short piece of text, 3573 it calls on the chart server to produce a QR code, a matrix of boxes that encode the 3574 text. 3575 That image can be grabbed with your cell phone's camera and interpreted as, 3576 for instance, a URL, saving you typing the URL into the phone's tiny keyboard. 3577 </p> 3578 <p> 3579 Here's the complete program. 3580 An explanation follows. 3581 </p> 3582 {{code "/doc/progs/eff_qr.go" `/package/` `$`}} 3583 <p> 3584 The pieces up to <code>main</code> should be easy to follow. 3585 The one flag sets a default HTTP port for our server. The template 3586 variable <code>templ</code> is where the fun happens. It builds an HTML template 3587 that will be executed by the server to display the page; more about 3588 that in a moment. 3589 </p> 3590 <p> 3591 The <code>main</code> function parses the flags and, using the mechanism 3592 we talked about above, binds the function <code>QR</code> to the root path 3593 for the server. Then <code>http.ListenAndServe</code> is called to start the 3594 server; it blocks while the server runs. 3595 </p> 3596 <p> 3597 <code>QR</code> just receives the request, which contains form data, and 3598 executes the template on the data in the form value named <code>s</code>. 3599 </p> 3600 <p> 3601 The template package <code>html/template</code> is powerful; 3602 this program just touches on its capabilities. 3603 In essence, it rewrites a piece of HTML text on the fly by substituting elements derived 3604 from data items passed to <code>templ.Execute</code>, in this case the 3605 form value. 3606 Within the template text (<code>templateStr</code>), 3607 double-brace-delimited pieces denote template actions. 3608 The piece from <code>{{html "{{if .}}"}}</code> 3609 to <code>{{html "{{end}}"}}</code> executes only if the value of the current data item, called <code>.</code> (dot), 3610 is non-empty. 3611 That is, when the string is empty, this piece of the template is suppressed. 3612 </p> 3613 <p> 3614 The two snippets <code>{{html "{{.}}"}}</code> say to show the data presented to 3615 the template—the query string—on the web page. 3616 The HTML template package automatically provides appropriate escaping so the 3617 text is safe to display. 3618 </p> 3619 <p> 3620 The rest of the template string is just the HTML to show when the page loads. 3621 If this is too quick an explanation, see the <a href="/pkg/html/template/">documentation</a> 3622 for the template package for a more thorough discussion. 3623 </p> 3624 <p> 3625 And there you have it: a useful web server in a few lines of code plus some 3626 data-driven HTML text. 3627 Go is powerful enough to make a lot happen in a few lines. 3628 </p> 3629 3630 <!-- 3631 TODO 3632 <pre> 3633 verifying implementation 3634 type Color uint32 3635 3636 // Check that Color implements image.Color and image.Image 3637 var _ image.Color = Black 3638 var _ image.Image = Black 3639 </pre> 3640 --> 3641