Home | History | Annotate | Download | only in doc

Lines Matching full:code

29 This document gives tips for writing clear, idiomatic Go code.
32 and <a href="/doc/code.html">How to Write Go Code</a>,
50 might be implemented, the documentation, code and examples in the
73 The <code>gofmt</code> program
74 (also available as <code>go fmt</code>, which
81 situation, run <code>gofmt</code>; if the answer doesn't
82 seem right, rearrange your program (or file a bug about <code>gofmt</code>),
89 <code>Gofmt</code> will do that for you. Given the
101 <code>gofmt</code> will line up the columns:
112 All Go code in the standard packages has been formatted with <code>gofmt</code>.
122 <dd>We use tabs for indentation and <code>gofmt</code> emits them by default.
132 Go needs fewer parentheses than C and Java: control structures (<code>if</code>,
133 <code>for</code>, <code>switch</code>) do not have parentheses in
146 Go provides C-style <code>/* */</code> block comments
147 and C++-style <code>//</code> line comments.
150 are useful within an expression or to disable large swaths of code.
154 The program?and web server?<code>godoc</code> processes
160 quality of the documentation <code>godoc</code> produces.
170 It will appear first on the <code>godoc</code> page and
209 on spacing for alignment&mdash;<code>godoc</code>, like <code>gofmt</code>,
212 annotations such as <code>_this_</code> will reproduce <i>verbatim</i> and should
214 One adjustment <code>godoc</code> does do is to display indented
217 <a href="/pkg/fmt/"><code>fmt</code> package</a> uses this to good effect.
221 Depending on the context, <code>godoc</code> might not even
248 If the name always begins the comment, the output of <code>godoc</code>
249 can usefully be run through <code>grep</code>.
260 If all the doc comments in the package began, "This function...", <code>grep</code>
328 the importing package can talk about <code>bytes.Buffer</code>. It's
338 across all source code, and in the rare case of a collision the
347 the package in <code>src/encoding/base64</code>
348 is imported as <code>"encoding/base64"</code> but has name <code>base64</code>,
349 not <code>encoding_base64</code> and not <code>encodingBase64</code>.
356 (Don't use the <code>import .</code> notation, which can simplify
358 For instance, the buffered reader type in the <code>bufio</code> package is called <code>Reader</code>,
359 not <code>BufReader</code>, because users see it as <code>bufio.Reader</code>,
362 because imported entities are always addressed with their package name, <code>bufio.Reader</code>
363 does not conflict with <code>io.Reader</code>.
364 Similarly, the function to make new instances of <code>ring.Ring</code>&mdash;which
366 normally be called <code>NewRing</code>, but since
367 <code>Ring</code> is the only type exported by the package, and since the
368 package is called <code>ring</code>, it's called just <code>New</code>,
369 which clients of the package see as <code>ring.New</code>.
374 Another short example is <code>once.Do</code>;
375 <code>once.Do(setup)</code> reads well and would not be improved by
376 writing <code>once.DoOrWaitUntilDone(setup)</code>.
387 to put <code>Get</code> into the getter's name. If you have a field called
388 <code>owner</code> (lower case, unexported), the getter method should be
389 called <code>Owner</code> (upper case, exported), not <code>GetOwner</code>.
392 A setter function, if needed, will likely be called <code>SetOwner</code>.
407 to construct an agent noun: <code>Reader</code>,
408 <code>Writer</code>, <code>Formatter</code>,
409 <code>CloseNotifier</code> etc.
415 <code>Read</code>, <code>Write</code>, <code>Close</code>, <code>Flush</code>,
416 <code>String</code> and so on have
423 call your string-converter method <code>String</code> not <code>ToString</code>.
429 Finally, the convention in Go is to use <code>MixedCaps</code>
430 or <code>mixedCaps</code> rather than underscores to write
445 (which includes words like <code>int</code> and <code>float64</code>),
468 <code>for</code> loop clauses, to separate the initializer, condition, and
470 statements on a line, should you write code that way.
476 control structure (<code>if</code>, <code>for</code>, <code>switch</code>,
477 or <code>select</code>) on the next line. If you do, a semicolon
503 There is no <code>do</code> or <code>while</code> loop, only a
505 <code>for</code>;
506 <code>switch</code> is more flexible;
507 <code>if</code> and <code>switch</code> accept an optional
508 initialization statement like that of <code>for</code>;
509 <code>break</code> and <code>continue</code> statements
512 multiway communications multiplexer, <code>select</code>.
521 In Go a simple <code>if</code> looks like this:
530 Mandatory braces encourage writing simple <code>if</code> statements
533 <code>return</code> or <code>break</code>.
537 Since <code>if</code> and <code>switch</code> accept an initialization
550 when an <code>if</code> statement doesn't flow into the next statement?that is,
551 the body ends in <code>break</code>, <code>continue</code>,
552 <code>goto</code>, or <code>return</code>?the unnecessary
553 <code>else</code> is omitted.
565 This is an example of a common situation where code must guard against a
566 sequence of error conditions. The code reads well if the
568 as they arise. Since error cases tend to end in <code>return</code>
569 statements, the resulting code needs no <code>else</code> statements.
590 <code>:=</code> short declaration form works.
591 The declaration that calls <code>os.Open</code> reads,
599 This statement declares two variables, <code>f</code> and <code>err</code>.
600 A few lines later, the call to <code>f.Stat</code> reads,
608 which looks as if it declares <code>d</code> and <code>err</code>.
609 Notice, though, that <code>err</code> appears in both statements.
610 This duplication is legal: <code>err</code> is declared by the first statement,
612 This means that the call to <code>f.Stat</code> uses the existing
613 <code>err</code> variable declared above, and just gives it a new value.
617 In a <code>:=</code> declaration a variable <code>v</code> may appear even
622 <li>this declaration is in the same scope as the existing declaration of <code>v</code>
623 (if <code>v</code> is already declared in an outer scope, the declaration will create a new variable §),</li>
624 <li>the corresponding value in the initialization is assignable to <code>v</code>, and</li>
630 making it easy to use a single <code>err</code> value, for example,
631 in a long <code>if-else</code> chain.
644 The Go <code>for</code> loop is similar to&mdash;but not the same as&mdash;C's.
645 It unifies <code>for</code>
646 and <code>while</code> and there is no <code>do-while</code>.
672 or reading from a channel, a <code>range</code> clause can
707 For strings, the <code>range</code> does more work for you, breaking out individual
708 Unicode code points by parsing the UTF-8.
711 (The name (with associated builtin type) <code>rune</code> is Go terminology for a
712 single Unicode code point.
733 Finally, Go has no comma operator and <code>++</code> and <code>--</code>
735 Thus if you want to run multiple variables in a <code>for</code>
736 you should use parallel assignment (although that precludes <code>++</code> and <code>--</code>).
748 Go's <code>switch</code> is more general than C's.
751 and if the <code>switch</code> has no expression it switches on
752 <code>true</code>.
754 <code>if</code>-<code>else</code>-<code>if</code>-<code>else</code>
755 chain as a <code>switch</code>.
788 languages, <code>break</code> statements can be used to terminate
789 a <code>switch</code> early.
822 Of course, the <code>continue</code> statement also accepts an optional label
828 <code>switch</code> statements:
858 assertion with the keyword <code>type</code> inside the parentheses.
889 error returns such as <code>-1</code> for <code>EOF</code>
895 error code secreted away in a volatile location.
896 In Go, <code>Write</code>
899 The signature of the <code>Write</code> method on files from
900 package <code>os</code> is:
909 written and a non-nil <code>error</code> when <code>n</code>
910 <code>!=</code> <code>len(b)</code>.
935 You could use it to scan the numbers in an input slice <code>b</code> like this:
951 the function begins; if the function executes a <code>return</code> statement
957 The names are not mandatory but they can make code shorter and clearer:
959 If we name the results of <code>nextInt</code> it becomes
960 obvious which returned <code>int</code>
971 of <code>io.ReadFull</code> that uses them well:
989 Go's <code>defer</code> statement schedules a function call (the
991 executing the <code>defer</code> returns. It's an unusual but
1023 Deferring a call to a function such as <code>Close</code> has two advantages. First, it
1046 Deferred functions are executed in LIFO order, so this code will cause
1047 <code>4 3 2 1 0</code> to be printed when the function returns. A
1067 functions are evaluated when the <code>defer</code> executes. The
1113 other languages, <code>defer</code> may seem peculiar, but its most
1116 <code>panic</code> and <code>recover</code> we'll see another
1122 <h3 id="allocation_new">Allocation with <code>new</code></h3>
1126 <code>new</code> and <code>make</code>.
1129 Let's talk about <code>new</code> first.
1134 <code>new(T)</code> allocates zeroed storage for a new item of type
1135 <code>T</code> and returns its address, a value of type <code>*T</code>.
1137 <code>T</code>.
1141 Since the memory returned by <code>new</code> is zeroed, it's helpful to arrange
1144 code>new</code> and get right to
1146 For example, the documentation for <code>bytes.Buffer</code> states that
1147 "the zero value for <code>Buffer</code> is an empty buffer ready to use."
1148 Similarly, <code>sync.Mutex</code> does not
1149 have an explicit constructor or <code>Init</code> method.
1150 Instead, the zero value for a <code>sync.Mutex</code>
1166 Values of type <code>SyncedBuffer</code> are also ready to use immediately upon allocation
1167 or just declaration. In the next snippet, both <code>p</code> and <code>v</code> will work
1181 package <code>os</code>.
1230 However, by labeling the elements explicitly as <i>field</i><code>:</code><i>value</i>
1241 a zero value for the type. The expressions <code>new(File)</code> and <code>&amp;File{}</code> are equivalent.
1247 In these examples, the initializations work regardless of the values of <code>Enone</code>,
1248 <code>Eio</code>, and <code>Einval</code>, as long as they are distinct.
1257 <h3 id="allocation_make">Allocation with <code>make</code></h3>
1261 The built-in function <code>make(T, </code><i>args</i><code>)</code> serves
1262 a purpose different from <code>new(T)</code>.
1265 value of type <code>T</code> (not <code>*T</code>).
1271 capacity, and until those items are initialized, the slice is <code>nil</code>.
1273 <code>make</code> initializes the internal data structure and prepares
1288 In contrast, <code>new([]int)</code> returns a pointer to a newly allocated, zeroed slice
1289 structure, that is, a pointer to a <code>nil</code> slice value.
1293 These examples illustrate the difference between <code>new</code> and
1294 <code>make</code>.
1310 Remember that <code>make</code> applies only to maps, slices and channels
1312 To obtain an explicit pointer allocate with <code>new</code> or take the address
1337 The size of an array is part of its type. The types <code>[10]int</code>
1338 and <code>[20]int</code> are distinct.
1377 passing a pointer to the underlying array. A <code>Read</code>
1381 <code>Read</code> method of the <code>File</code> type in package
1382 <code>os</code>:
1391 <code>buf</code>, <i>slice</i> (here used as a verb) the buffer.
1416 function <code>cap</code>, reports the maximum length the slice may
1420 <code>len</code> and <code>cap</code> are legal when applied to the
1421 <code>nil</code> slice, and return 0.
1441 We must return the slice afterwards because, although <code>Append</code>
1442 can modify the elements of <code>slice</code>, the slice itself (the run-time data
1448 <code>append</code> built-in function. To understand that function's
1469 That can be a common situation, as in our <code>LinesOfText</code>
1564 up a non-existent key will return <code>0</code>.
1565 A set can be implemented as a map with value type <code>bool</code>.
1566 Set the map entry to <code>true</code> to put the value in the set, and then
1582 a zero value. Is there an entry for <code>"UTC"</code>
1593 In this example, if <code>tz</code> is present, <code>seconds</code>
1594 will be set appropriately and <code>ok</code> will be true; if not,
1595 <code>seconds</code> will be set to zero and <code>ok</code> will
1610 you can use the <a href="#blank">blank identifier</a> (<code>_</code>)
1617 To delete a map entry, use the <code>delete</code>
1629 Formatted printing in Go uses a style similar to C's <code>printf</code>
1630 family but is richer and more general. The functions live in the <code>fmt</code>
1631 package and have capitalized names: <code>fmt.Printf</code>, <code>fmt.Fprintf</code>,
1632 <code>fmt.Sprintf</code> and so on. The string functions (<code>Sprintf</code> etc.)
1636 You don't need to provide a format string. For each of <code>Printf</code>,
1637 <code>Fprintf</code> and <code>Sprintf</code> there is another pair
1638 of functions, for instance <code>Print</code> and <code>Println</code>.
1640 format for each argument. The <code>Println</code> versions also insert a blank
1642 the <code>Print</code> versions add blanks only if the operand on neither side is a string.
1652 The formatted print functions <code>fmt.Fprint</code>
1654 that implements the <code>io.Writer</code> interface; the variables <code>os.Stdout</code>
1655 and <code>os.Stderr</code> are familiar instances.
1658 Here things start to diverge from C. First, the numeric formats such as <code>%d</code>
1674 the catchall format <code>%v</code> (for &ldquo;value&rdquo;); the result is exactly
1675 what <code>Print</code> and <code>Println</code> would produce.
1690 When printing a struct, the modified format <code>%+v</code> annotates the
1692 format <code>%#v</code> prints the value in full Go syntax.
1717 That quoted string format is also available through <code>%q</code> when
1718 applied to a value of type <code>string</code> or <code>[]byte</code>.
1719 The alternate format <code>%#q</code> will use backquotes instead if possible.
1720 (The <code>%q</code> format also applies to integers and runes, producing a
1722 Also, <code>%x</code> works on strings, byte arrays and byte slices as well as
1724 a space in the format (<code>%&nbsp;x</code>) it puts spaces between the bytes.
1727 Another handy format is <code>%T</code>, which prints the <em>type</em> of a value.
1740 a method with the signature <code>String() string</code> on the type.
1741 For our simple type <code>T</code>, that might look like this.
1756 (If you need to print <em>values</em> of type <code>T</code> as well as pointers to <code>T</code>,
1757 the receiver for <code>String</code> must be of value type; this example used a pointer because
1763 Our <code>String</code> method is able to call <code>Sprintf</code> because the
1766 however: don't construct a <code>String</code> method by calling
1767 <code>Sprintf</code> in a way that will recur into your <code>String</code>
1768 method indefinitely. This can happen if the <code>Sprintf</code>
1800 The signature of <code>Printf</code> uses the type <code>...interface{}</code>
1808 Within the function <code>Printf</code>, <code>v</code> acts like a variable of type
1809 <code>[]interface{}</code> but if it is passed to another variadic function, it acts like
1812 function <code>log.Println</code> we used above. It passes its arguments directly to
1813 <code>fmt.Sprintln</code> for the actual formatting.
1822 We write <code>...</code> after <code>v</code> in the nested call to <code>Sprintln</code> to tell the
1823 compiler to treat <code>v</code> as a list of arguments; otherwise it would just pass
1824 <code>v</code> as a single slice argument.
1827 There's even more to printing than we've covered here. See the <code>godoc</code> documentation
1828 for package <code>fmt</code> for the details.
1831 By the way, a <code>...</code> parameter can be of a specific type, for instance <code>...int</code>
1849 the <code>append</code> built-in function. The signature of <code>append</code>
1850 is different from our custom <code>Append</code> function above.
1858 actually write a function in Go where the type <code>T</code>
1860 That's why <code>append</code> is built in: it needs support from the
1864 What <code>append</code> does is append the elements to the end of
1866 because, as with our hand-written <code>Append</code>, the underlying
1875 prints <code>[1 2 3 4 5 6]</code>. So <code>append</code> works a
1876 little like <code>Printf</code>, collecting an arbitrary number of
1880 But what if we wanted to do what our <code>Append</code> does and
1881 append a slice to a slice? Easy: use <code>...</code> at the call
1882 site, just as we did in the call to <code>Output</code> above. This
1892 Without that <code>...</code>, it wouldn't compile because the types
1893 would be wrong; <code>y</code> is not of type <code>int</code>.
1916 <code>1&lt;&lt;3</code> is a constant expression, while
1917 <code>math.Sin(math.Pi/4)</code> is not because
1918 the function call to <code>math.Sin</code> needs
1923 In Go, enumerated constants are created using the <code>iota</code>
1924 enumerator. Since <code>iota</code> can be part of an expression and
1928 {{code "/doc/progs/eff_bytesize.go" `/^type ByteSize/` `/^\)/`}}
1930 The ability to attach a method such as <code>String</code> to any
1934 scalar types such as floating-point types like <code>ByteSize</code>.
1936 {{code "/doc/progs/eff_bytesize.go" `/^func.*ByteSize.*String/` `/^}/`}}
1938 The expression <code>YB</code> prints as <code>1.00YB</code>,
1939 while <code>ByteSize(1e13)</code> prints as <code>9.09TB</code>.
1943 The use here of <code>Sprintf</code>
1944 to implement <code>ByteSize</code>'s <code>String</code> method is safe
1946 because it calls <code>Sprintf</code> with <code>%f</code>,
1947 which is not a string format: <code>Sprintf</code> will only call
1948 the <code>String</code> method when it wants a string, and <code>%f</code>
1969 Finally, each source file can define its own niladic <code>init</code> function to
1971 <code>init</code> functions.)
1972 And finally means finally: <code>init</code> is called after all the
1979 a common use of <code>init</code> functions is to verify or repair
2003 As we saw with <code>ByteSize</code>,
2008 In the discussion of slices above, we wrote an <code>Append</code>
2023 <i>pointer</i> to a <code>ByteSlice</code> as its receiver, so the
2035 like a standard <code>Write</code> method, like this,
2046 then the type <code>*ByteSlice</code> satisfies the standard interface
2047 <code>io.Writer</code>, which is handy. For instance, we can
2055 We pass the address of a <code>ByteSlice</code>
2056 because only <code>*ByteSlice</code> satisfies <code>io.Writer</code>.
2070 In our example, the variable <code>b</code> is addressable, so we can call
2071 its <code>Write</code> method with just <code>b.Write</code>. The compiler
2072 will rewrite that to <code>(&amp;b).Write</code> for us.
2076 By the way, the idea of using <code>Write</code> on a slice of bytes
2077 is central to the implementation of <code>bytes.Buffer</code>.
2087 custom printers can be implemented by a <code>String</code> method
2088 while <code>Fprintf</code> can generate output to anything
2089 with a <code>Write</code> method.
2090 Interfaces with only one or two methods are common in Go code, and are
2091 usually given a name derived from the method, such as <code>io.Writer</code>
2092 for something that implements <code>Write</code>.
2097 by the routines in package <code>sort</code> if it implements
2098 <code>sort.Interface</code>, which contains <code>Len()</code>,
2099 <code>Less(i, j int) bool</code>, and <code>Swap(i, j int)</code>,
2101 In this contrived example <code>Sequence</code> satisfies both.
2103 {{code "/doc/progs/eff_sequence.go" `/^type/` "$"}}
2108 The <code>String</code> method of <code>Sequence</code> is recreating the
2109 work that <code>Sprint</code> already does for slices. We can share the
2110 effort if we convert the <code>Sequence</code> to a plain
2111 <code>[]int</code> before calling <code>Sprint</code>.
2121 <code>Sprintf</code> safely from a <code>String</code> method.
2122 Because the two types (<code>Sequence</code> and <code>[]int</code>)
2133 type <code>sort.IntSlice</code> to reduce the entire example
2146 Now, instead of having <code>Sequence</code> implement multiple
2148 converted to multiple types (<code>Sequence</code>, <code>sort.IntSlice</code>
2149 and <code>[]int</code>), each of which does some part of the job.
2158 Here's a simplified version of how the code under <code>fmt.Printf</code> turns a value into
2161 <code>String</code> method we want the result of calling the method.
2184 What if there's only one type we care about? If we know the value holds a <code>string</code>
2189 type rather than the <code>type</code> keyword:
2197 and the result is a new value with the static type <code>typeName</code>.
2222 If the type assertion fails, <code>str</code> will still exist and be of type string, but it will have
2227 As an illustration of the capability, here's an <code>if</code>-<code>else</code>
2255 both <code>crc32.NewIEEE</code> and <code>adler32.New</code>
2256 return the interface type <code>hash.Hash32</code>.
2259 the rest of the code is unaffected by the change of algorithm.
2263 in the various <code>crypto</code> packages to be
2265 The <code>Block</code> interface
2266 in the <code>crypto/cipher</code> package specifies the
2269 Then, by analogy with the <code>bufio</code> package,
2272 by the <code>Stream</code> interface, without
2276 The <code>crypto/cipher</code> interfaces look like this:
2302 <code>NewCTR</code> applies not
2304 implementation of the <code>Block</code> interface and any
2305 <code>Stream</code>. Because they return
2308 calls must be edited, but because the surrounding code must treat the result only
2309 as a <code>Stream</code>, it won't notice the difference.
2315 satisfy an interface. One illustrative example is in the <code>http</code>
2316 package, which defines the <code>Handler</code> interface. Any object
2317 that implements <code>Handler</code> can serve HTTP requests.
2325 <code>ResponseWriter</code> is itself an interface that provides access
2327 Those methods include the standard <code>Write</code> method, so an
2328 <code>http.ResponseWriter</code> can be used wherever an <code>io.Writer</code>
2330 <code>Request</code> is a struct containing a parsed representation
2352 (Keeping with our theme, note how <code>Fprintf</code> can print to an
2353 <code>http.ResponseWriter</code>.)
2363 But why make <code>Counter</code> a struct? An integer is all that's needed.
2390 Finally, let's say we wanted to present on <code>/args</code> the arguments
2400 How do we turn that into an HTTP server? We could make <code>ArgServer</code>
2404 The <code>http</code> package contains this code:
2419 <code>HandlerFunc</code> is a type with a method, <code>ServeHTTP</code>,
2421 of the method: the receiver is a function, <code>f</code>, and the method
2422 calls <code>f</code>. That may seem odd but it's not that different from, say,
2426 To make <code>ArgServer</code> into an HTTP server, we first modify it
2436 <code>ArgServer</code> now has same signature as <code>HandlerFunc</code>,
2438 just as we converted <code>Sequence</code> to <code>IntSlice</code>
2439 to access <code>IntSlice.Sort</code>.
2440 The code to set it up is concise:
2446 When someone visits the page <code>/args</code>,
2447 the handler installed at that page has value <code>ArgServer</code>
2448 and type <code>HandlerFunc</code>.
2449 The HTTP server will invoke the method <code>ServeHTTP</code>
2450 of that type, with <code>ArgServer</code> as the receiver, which will in turn call
2451 <code>ArgServer</code> (via the invocation <code>f(c, req)</code>
2452 inside <code>HandlerFunc.ServeHTTP</code>).
2465 <a href="#for"><code>for</code> <code>range</code> loops</a>
2469 It's a bit like writing to the Unix <code>/dev/null</code> file:
2479 The use of a blank identifier in a <code>for</code> <code>range</code> loop is a
2502 Occasionally you'll see code that discards the error value in order
2508 // Bad! This code will crash if path does not exist.
2531 (<code>fmt</code> and <code>io</code>)
2532 and an unused variable (<code>fd</code>),
2534 code so far is correct.
2536 {{code "/doc/progs/eff_unused1.go" `/package/` `$`}}
2540 Similarly, assigning the unused variable <code>fd</code>
2544 {{code "/doc/progs/eff_unused2.go" `/package/` `$`}}
2555 An unused import like <code>fmt</code> or <code>io</code> in the
2557 blank assignments identify code as a work in progress.
2560 For example, during its <code>init</code> function,
2561 the <code><a href="/pkg/net/http/pprof/">net/http/pprof</a></code>
2586 For example, passing an <code>*os.File</code> to a function
2587 expecting an <code>io.Reader</code> will not compile unless
2588 <code>*os.File</code> implements the <code>io.Reader</code> interface.
2593 One instance is in the <code><a href="/pkg/encoding/json/">encoding/json</a></code>
2594 package, which defines a <code><a href="/pkg/encoding/json/#Marshaler">Marshaler</a></code>
2621 <code><a href="/pkg/encoding/json/#RawMessage">json.RawMessage</a></code>?needs
2623 <code>json.Marshaler</code>, but there are no static conversions that would
2635 <code>*RawMessage</code> to a <code>Marshaler</code>
2636 requires that <code>*RawMessage</codecode>Marshaler</code>,
2638 Should the <code>json.Marshaler</code> interface change, this package
2648 when there are no static conversions already present in the code,
2663 We've mentioned the <code>io.Reader</code> and <code>io.Writer</code> interfaces before;
2676 The <code>io</code> package also exports several other interfaces
2678 For instance, there is <code>io.ReadWriter</code>, an interface
2679 containing both <code>Read</code> and <code>Write</code>.
2680 We could specify <code>io.ReadWriter</code> by listing the
2692 This says just what it looks like: A <code>ReadWriter</code> can do
2693 what a <code>Reader</code> does <em>and</em> what a <code>Writer</code>
2700 implications. The <code>bufio</code> package has two struct types,
2701 <code>bufio.Reader</code> and <code>bufio.Writer</code>, each of
2703 <code>io</code>.
2704 And <code>bufio</code> also implements a buffered reader/writer,
2721 The <code>ReadWriter</code> struct could be written as
2731 satisfy the <code>io</code> interfaces, we would also need
2741 The methods of embedded types come along for free, which means that <code>bufio.ReadWriter</code>
2742 not only has the methods of <code>bufio.Reader</code> and <code>bufio.Writer</code>,
2744 <code>io.Reader</code>,
2745 <code>io.Writer</code>, and
2746 <code>io.ReadWriter</code>.
2752 In our example, when the <code>Read</code> method of a <code>bufio.ReadWriter</code> is
2754 the receiver is the <code>reader</code> field of the <code>ReadWriter</code>, not the
2755 <code>ReadWriter</code> itself.
2768 The <code>Job</code> type now has the <code>Log</code>, <code>Logf</code>
2770 methods of <code>*log.Logger</code>. We could have given the <code>Logger</code>
2773 log to the <code>Job</code>:
2779 The <code>Logger</code> is a regular field of the <code>Job</code> struct,
2780 so we can initialize it in the usual way inside the constructor for <code>Job</code>, like this,
2796 in the <code>Read</code> method of our <code>ReaderWriter</code> struct.
2798 <code>*log.Logger</code> of a <code>Job</code> variable <code>job</code>,
2799 we would write <code>job.Logger</code>,
2800 which would be useful if we wanted to refine the methods of <code>Logger</code>.
2810 First, a field or method <code>X</code> hides any other item <code>X</code> in a more deeply
2812 If <code>log.Logger</code> contained a field or method called <code>Command</code>, the <code>Command</code> field
2813 of <code>Job</code> would dominate it.
2817 it would be erroneous to embed <code>log.Logger</code> if the <code>Job</code> struct
2818 contained another field or method called <code>Logger</code>.
2883 Prefix a function or method call with the <code>go</code>
2887 <code>&amp;</code> notation for running a command in the
2916 Like maps, channels are allocated with <code>make</code>, and
2957 to <code>handle</code>, which sends a value into the channel, processes
2961 simultaneous calls to <code>process</code>.
2981 Once <code>MaxOutstanding</code> handlers are executing <code>process</code>,
2987 This design has a problem, though: <code>Serve</code>
2989 every incoming request, even though only <code>MaxOutstanding</code>
2992 We can address that deficiency by changing <code>Serve</code> to
3009 The bug is that in a Go <code>for</code> loop, the loop variable
3010 is reused for each iteration, so the <code>req</code>
3013 We need to make sure that <code>req</code> is unique for each goroutine.
3014 Here's one way to do that, passing the value of <code>req</code> as an argument
3065 number of <code>handle</code> goroutines all reading from the request
3068 calls to <code>process</code>.
3069 This <code>Serve</code> function also accepts a channel on which
3098 In the example in the previous section, <code>handle</code> was
3102 Here's a schematic definition of type <code>Request</code>.
3141 code is a framework for a rate-limited, parallel, non-blocking RPC
3192 The function <code><a href="/pkg/runtime#NumCPU">runtime.NumCPU</a></code>
3200 <code><a href="/pkg/runtime#GOMAXPROCS">runtime.GOMAXPROCS</a></code>,
3204 It defaults to the value of <code>runtime.NumCPU</code> but can be
3234 <code>serverChan</code>.
3276 The client attempts to retrieve a buffer from <code>freeList</code>;
3278 The server's send to <code>freeList</code> puts <code>b</code> back
3282 (The <code>default</code> clauses in the <code>select</code>
3284 meaning that the <code>selects</code> never block.)
3299 For example, as we'll see, <code>os.Open</code> doesn't
3300 just return a <code>nil</code> pointer on failure, it also returns an
3305 By convention, errors have type <code>error</code>,
3317 As mentioned, alongside the usual <code>*os.File</code>
3318 return value, <code>os.Open</code> also returns an
3320 If the file is opened successfully, the error will be <code>nil</code>,
3322 <code>os.PathError</code>:
3338 <code>PathError</code>'s <code>Error</code> generates
3355 <code>image</code>, the string representation for a decoding error due to an
3362 errors and extract details. For <code>PathErrors</code>
3363 this might include examining the internal <code>Err</code>
3382 The second <code>if</code> statement here is another <a href="#interface_conversions">type assertion</a>.
3383 If it fails, <code>ok</code> will be false, and <code>e</code>
3384 will be <code>nil</code>.
3385 If it succeeds, <code>ok</code> will be true, which means the
3386 error was of type <code>*os.PathError</code>, and then so is <code>e</code>,
3394 <code>error</code> as an extra return value. The canonical
3395 <code>Read</code> method is a well-known instance; it returns a byte
3396 count and an <code>error</code>. But what if the error is
3401 For this purpose, there is a built-in function <code>panic</code>
3428 avoid <code>panic</code>. If the problem can be masked or worked
3448 When <code>panic</code> is called, including implicitly for run-time
3454 use the built-in function <code>recover</code> to regain control
3459 A call to <code>recover</code> stops the unwinding and returns the
3460 argument passed to <code>panic</code>. Because the only code that
3461 runs while unwinding is inside deferred functions, <code>recover</code>
3466 One application of <code>recover</code> is to shut down a failing goroutine
3488 In this example, if <code>do(work)</code> panics, the result will be
3491 calling <code>recover</code> handles the condition completely.
3495 Because <code>recover</code> always returns <code>nil</code> unless called directly
3496 from a deferred function, deferred code can call library routines that themselves
3497 use <code>panic</code> and <code>recover</code> without failing. As an example,
3498 the deferred function in <code>safelyDo</code> might call a logging function before
3499 calling <code>recover</code>, and that logging code would run unaffected
3504 With our recovery pattern in place, the <code>do</code>
3506 cleanly by calling <code>panic</code>. We can use that idea to
3508 idealized version of a <code>regexp</code> package, which reports
3509 parsing errors by calling <code>panic</code> with a local
3510 error type. Here's the definition of <code>Error</code>,
3511 an <code>error</code> method, and the <code>Compile</code> function.
3542 If <code>doParse</code> panics, the recovery block will set the
3543 return value to <code>nil</code>&mdash;deferred functions can modify
3545 to <code>err</code>, that the problem was a parse error by asserting
3546 that it has the local type <code>Error</code>.
3551 as an index out of bounds, the code will fail even though we
3552 are using <code>panic</code> and <code>recover</code> to handle
3557 With error handling in place, the <code>error</code> method (because it's a
3559 as the builtin <code>error</code> type)
3572 <code>Parse</code> turns its internal <code>panic</code> calls into
3573 <code>error</code> values; it does not expose <code>panics</code>
3583 display only the original value, you can write a little more code to
3600 it calls on the chart server to produce a QR code, a matrix of boxes that encode the
3609 {{code "/doc/progs/eff_qr.go" `/package/` `$`}}
3611 The pieces up to <code>main</code> should be easy to follow.
3613 variable <code>templ</code> is where the fun happens. It builds an HTML template
3618 The <code>main</code
3619 we talked about above, binds the function <code>QR</code> to the root path
3620 for the server. Then <code>http.ListenAndServe</code> is called to start the
3624 <code>QR</code> just receives the request, which contains form data, and
3625 executes the template on the data in the form value named <code>s</code>.
3628 The template package <code>html/template</code> is powerful;
3631 from data items passed to <code>templ.Execute</code>, in this case the
3633 Within the template text (<code>templateStr</code>),
3635 The piece from <code>{{html "{{if .}}"}}</code>
3636 to <code>{{html "{{end}}"}}</code> executes only if the value of the current data item, called <code>.</code> (dot),
3641 The two snippets <code>{{html "{{.}}"}}</code> say to show the data presented to
3652 And there you have it: a useful web server in a few lines of code plus some