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