"Fossies" - the Fresh Open Source Software Archive

Member "go/doc/effective_go.html" (9 Sep 2020, 116734 Bytes) of package /windows/misc/go1.14.9.windows-386.zip:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) HTML source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file.

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