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