davideisinger.com

My personal website
Log | Files | Refs | README

go-dev-vfin4x.txt (107492B)


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