github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/doc/go_faq.html (about) 1 <!--{ 2 "Title": "FAQ", 3 "Path": "/doc/faq" 4 }--> 5 6 <h2 id="Origins">Origins</h2> 7 8 <h3 id="What_is_the_purpose_of_the_project"> 9 What is the purpose of the project?</h3> 10 11 <p> 12 No major systems language has emerged in over a decade, but over that time 13 the computing landscape has changed tremendously. There are several trends: 14 </p> 15 16 <ul> 17 <li> 18 Computers are enormously quicker but software development is not faster. 19 <li> 20 Dependency management is a big part of software development today but the 21 “header files” of languages in the C tradition are antithetical to clean 22 dependency analysis—and fast compilation. 23 <li> 24 There is a growing rebellion against cumbersome type systems like those of 25 Java and C++, pushing people towards dynamically typed languages such as 26 Python and JavaScript. 27 <li> 28 Some fundamental concepts such as garbage collection and parallel computation 29 are not well supported by popular systems languages. 30 <li> 31 The emergence of multicore computers has generated worry and confusion. 32 </ul> 33 34 <p> 35 We believe it's worth trying again with a new language, a concurrent, 36 garbage-collected language with fast compilation. Regarding the points above: 37 </p> 38 39 <ul> 40 <li> 41 It is possible to compile a large Go program in a few seconds on a single computer. 42 <li> 43 Go provides a model for software construction that makes dependency 44 analysis easy and avoids much of the overhead of C-style include files and 45 libraries. 46 <li> 47 Go's type system has no hierarchy, so no time is spent defining the 48 relationships between types. Also, although Go has static types the language 49 attempts to make types feel lighter weight than in typical OO languages. 50 <li> 51 Go is fully garbage-collected and provides fundamental support for 52 concurrent execution and communication. 53 <li> 54 By its design, Go proposes an approach for the construction of system 55 software on multicore machines. 56 </ul> 57 58 <h3 id="What_is_the_status_of_the_project"> 59 What is the status of the project?</h3> 60 61 <p> 62 Go became a public open source project on November 10, 2009. 63 After a couple of years of very active design and development, stability was called for and 64 Go 1 was <a href="http://blog.golang.org/2012/03/go-version-1-is-released.html">released</a> 65 on March 28, 2012. 66 Go 1, which includes a <a href="/ref/spec">language specification</a>, 67 <a href="/pkg/">standard libraries</a>, 68 and <a href="/cmd/go/">custom tools</a>, 69 provides a stable foundation for creating reliable products, projects, and publications. 70 </p> 71 72 <p> 73 With that stability established, we are using Go to develop programs, products, and tools rather than 74 actively changing the language and libraries. 75 In fact, the purpose of Go 1 is to provide <a href="/doc/go1compat.html">long-term stability</a>. 76 Backwards-incompatible changes will not be made to any Go 1 point release. 77 We want to use what we have to learn how a future version of Go might look, rather than to play with 78 the language underfoot. 79 </p> 80 81 <p> 82 Of course, development will continue on Go itself, but the focus will be on performance, reliability, 83 portability and the addition of new functionality such as improved support for internationalization. 84 </p> 85 86 <p> 87 There may well be a Go 2 one day, but not for a few years and it will be influenced by what we learn using Go 1 as it is today. 88 </p> 89 90 <h3 id="What_is_the_origin_of_the_name"> 91 What is the origin of the name?</h3> 92 93 <p> 94 “Ogle” would be a good name for a Go debugger. 95 </p> 96 97 <h3 id="Whats_the_origin_of_the_mascot"> 98 What's the origin of the mascot?</h3> 99 100 <p> 101 The mascot and logo were designed by 102 <a href="http://reneefrench.blogspot.com">Renée French</a>, who also designed 103 <a href="http://plan9.bell-labs.com/plan9/glenda.html">Glenda</a>, 104 the Plan 9 bunny. 105 The gopher is derived from one she used for an <a href="http://wfmu.org/">WFMU</a> 106 T-shirt design some years ago. 107 The logo and mascot are covered by the 108 <a href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0</a> 109 license. 110 </p> 111 112 <h3 id="history"> 113 What is the history of the project?</h3> 114 <p> 115 Robert Griesemer, Rob Pike and Ken Thompson started sketching the 116 goals for a new language on the white board on September 21, 2007. 117 Within a few days the goals had settled into a plan to do something 118 and a fair idea of what it would be. Design continued part-time in 119 parallel with unrelated work. By January 2008, Ken had started work 120 on a compiler with which to explore ideas; it generated C code as its 121 output. By mid-year the language had become a full-time project and 122 had settled enough to attempt a production compiler. In May 2008, 123 Ian Taylor independently started on a GCC front end for Go using the 124 draft specification. Russ Cox joined in late 2008 and helped move the language 125 and libraries from prototype to reality. 126 </p> 127 128 <p> 129 Go became a public open source project on November 10, 2009. 130 Many people from the community have contributed ideas, discussions, and code. 131 </p> 132 133 <h3 id="creating_a_new_language"> 134 Why are you creating a new language?</h3> 135 <p> 136 Go was born out of frustration with existing languages and 137 environments for systems programming. Programming had become too 138 difficult and the choice of languages was partly to blame. One had to 139 choose either efficient compilation, efficient execution, or ease of 140 programming; all three were not available in the same mainstream 141 language. Programmers who could were choosing ease over 142 safety and efficiency by moving to dynamically typed languages such as 143 Python and JavaScript rather than C++ or, to a lesser extent, Java. 144 </p> 145 146 <p> 147 Go is an attempt to combine the ease of programming of an interpreted, 148 dynamically typed 149 language with the efficiency and safety of a statically typed, compiled language. 150 It also aims to be modern, with support for networked and multicore 151 computing. Finally, it is intended to be <i>fast</i>: it should take 152 at most a few seconds to build a large executable on a single computer. 153 To meet these goals required addressing a number of 154 linguistic issues: an expressive but lightweight type system; 155 concurrency and garbage collection; rigid dependency specification; 156 and so on. These cannot be addressed well by libraries or tools; a new 157 language was called for. 158 </p> 159 160 <p> 161 The article <a href="http://talks.golang.org/2012/splash.article">Go at Google</a> 162 discusses the background and motivation behind the design of the Go language, 163 as well as providing more detail about many of the answers presented in this FAQ. 164 </p> 165 166 <h3 id="ancestors"> 167 What are Go's ancestors?</h3> 168 <p> 169 Go is mostly in the C family (basic syntax), 170 with significant input from the Pascal/Modula/Oberon 171 family (declarations, packages), 172 plus some ideas from languages 173 inspired by Tony Hoare's CSP, 174 such as Newsqueak and Limbo (concurrency). 175 However, it is a new language across the board. 176 In every respect the language was designed by thinking 177 about what programmers do and how to make programming, at least the 178 kind of programming we do, more effective, which means more fun. 179 </p> 180 181 <h3 id="principles"> 182 What are the guiding principles in the design?</h3> 183 <p> 184 Programming today involves too much bookkeeping, repetition, and 185 clerical work. As Dick Gabriel says, “Old programs read 186 like quiet conversations between a well-spoken research worker and a 187 well-studied mechanical colleague, not as a debate with a compiler. 188 Who'd have guessed sophistication bought such noise?” 189 The sophistication is worthwhile—no one wants to go back to 190 the old languages—but can it be more quietly achieved? 191 </p> 192 <p> 193 Go attempts to reduce the amount of typing in both senses of the word. 194 Throughout its design, we have tried to reduce clutter and 195 complexity. There are no forward declarations and no header files; 196 everything is declared exactly once. Initialization is expressive, 197 automatic, and easy to use. Syntax is clean and light on keywords. 198 Stuttering (<code>foo.Foo* myFoo = new(foo.Foo)</code>) is reduced by 199 simple type derivation using the <code>:=</code> 200 declare-and-initialize construct. And perhaps most radically, there 201 is no type hierarchy: types just <i>are</i>, they don't have to 202 announce their relationships. These simplifications allow Go to be 203 expressive yet comprehensible without sacrificing, well, sophistication. 204 </p> 205 <p> 206 Another important principle is to keep the concepts orthogonal. 207 Methods can be implemented for any type; structures represent data while 208 interfaces represent abstraction; and so on. Orthogonality makes it 209 easier to understand what happens when things combine. 210 </p> 211 212 <h2 id="Usage">Usage</h2> 213 214 <h3 id="Is_Google_using_go_internally"> Is Google using Go internally?</h3> 215 216 <p> 217 Yes. There are now several Go programs deployed in 218 production inside Google. A public example is the server behind 219 <a href="http://golang.org">http://golang.org</a>. 220 It's just the <a href="/cmd/godoc"><code>godoc</code></a> 221 document server running in a production configuration on 222 <a href="https://developers.google.com/appengine/">Google App Engine</a>. 223 </p> 224 225 <p> 226 Other examples include the <a href="https://code.google.com/p/vitess/">Vitess</a> 227 system for large-scale SQL installations and Google's download server, <code>dl.google.com</code>, 228 which delivers Chrome binaries and other large installables such as <code>apt-get</code> 229 packages. 230 </p> 231 232 <h3 id="Do_Go_programs_link_with_Cpp_programs"> 233 Do Go programs link with C/C++ programs?</h3> 234 235 <p> 236 There are two Go compiler implementations, <code>gc</code> 237 (the <code>6g</code> program and friends) and <code>gccgo</code>. 238 <code>Gc</code> uses a different calling convention and linker and can 239 therefore only be linked with C programs using the same convention. 240 There is such a C compiler but no C++ compiler. 241 <code>Gccgo</code> is a GCC front-end that can, with care, be linked with 242 GCC-compiled C or C++ programs. 243 </p> 244 245 <p> 246 The <a href="/cmd/cgo/">cgo</a> program provides the mechanism for a 247 “foreign function interface” to allow safe calling of 248 C libraries from Go code. SWIG extends this capability to C++ libraries. 249 </p> 250 251 252 <h3 id="Does_Go_support_Google_protocol_buffers"> 253 Does Go support Google's protocol buffers?</h3> 254 255 <p> 256 A separate open source project provides the necessary compiler plugin and library. 257 It is available at 258 <a href="http://code.google.com/p/goprotobuf/">http://code.google.com/p/goprotobuf/</a> 259 </p> 260 261 262 <h3 id="Can_I_translate_the_Go_home_page"> 263 Can I translate the Go home page into another language?</h3> 264 265 <p> 266 Absolutely. We encourage developers to make Go Language sites in their own languages. 267 However, if you choose to add the Google logo or branding to your site 268 (it does not appear on <a href="http://golang.org/">golang.org</a>), 269 you will need to abide by the guidelines at 270 <a href="http://www.google.com/permissions/guidelines.html">http://www.google.com/permissions/guidelines.html</a> 271 </p> 272 273 <h2 id="Design">Design</h2> 274 275 <h3 id="unicode_identifiers"> 276 What's up with Unicode identifiers?</h3> 277 278 <p> 279 It was important to us to extend the space of identifiers from the 280 confines of ASCII. Go's rule—identifier characters must be 281 letters or digits as defined by Unicode—is simple to understand 282 and to implement but has restrictions. Combining characters are 283 excluded by design, for instance. 284 Until there 285 is an agreed external definition of what an identifier might be, 286 plus a definition of canonicalization of identifiers that guarantees 287 no ambiguity, it seemed better to keep combining characters out of 288 the mix. Thus we have a simple rule that can be expanded later 289 without breaking programs, one that avoids bugs that would surely arise 290 from a rule that admits ambiguous identifiers. 291 </p> 292 293 <p> 294 On a related note, since an exported identifier must begin with an 295 upper-case letter, identifiers created from “letters” 296 in some languages can, by definition, not be exported. For now the 297 only solution is to use something like <code>X日本語</code>, which 298 is clearly unsatisfactory; we are considering other options. The 299 case-for-visibility rule is unlikely to change however; it's one 300 of our favorite features of Go. 301 </p> 302 303 <h3 id="Why_doesnt_Go_have_feature_X">Why does Go not have feature X?</h3> 304 305 <p> 306 Every language contains novel features and omits someone's favorite 307 feature. Go was designed with an eye on felicity of programming, speed of 308 compilation, orthogonality of concepts, and the need to support features 309 such as concurrency and garbage collection. Your favorite feature may be 310 missing because it doesn't fit, because it affects compilation speed or 311 clarity of design, or because it would make the fundamental system model 312 too difficult. 313 </p> 314 315 <p> 316 If it bothers you that Go is missing feature <var>X</var>, 317 please forgive us and investigate the features that Go does have. You might find that 318 they compensate in interesting ways for the lack of <var>X</var>. 319 </p> 320 321 <h3 id="generics"> 322 Why does Go not have generic types?</h3> 323 <p> 324 Generics may well be added at some point. We don't feel an urgency for 325 them, although we understand some programmers do. 326 </p> 327 328 <p> 329 Generics are convenient but they come at a cost in 330 complexity in the type system and run-time. We haven't yet found a 331 design that gives value proportionate to the complexity, although we 332 continue to think about it. Meanwhile, Go's built-in maps and slices, 333 plus the ability to use the empty interface to construct containers 334 (with explicit unboxing) mean in many cases it is possible to write 335 code that does what generics would enable, if less smoothly. 336 </p> 337 338 <p> 339 This remains an open issue. 340 </p> 341 342 <h3 id="exceptions"> 343 Why does Go not have exceptions?</h3> 344 <p> 345 We believe that coupling exceptions to a control 346 structure, as in the <code>try-catch-finally</code> idiom, results in 347 convoluted code. It also tends to encourage programmers to label 348 too many ordinary errors, such as failing to open a file, as 349 exceptional. 350 </p> 351 352 <p> 353 Go takes a different approach. For plain error handling, Go's multi-value 354 returns make it easy to report an error without overloading the return value. 355 <a href="/doc/articles/error_handling.html">A canonical error type, coupled 356 with Go's other features</a>, makes error handling pleasant but quite different 357 from that in other languages. 358 </p> 359 360 <p> 361 Go also has a couple 362 of built-in functions to signal and recover from truly exceptional 363 conditions. The recovery mechanism is executed only as part of a 364 function's state being torn down after an error, which is sufficient 365 to handle catastrophe but requires no extra control structures and, 366 when used well, can result in clean error-handling code. 367 </p> 368 369 <p> 370 See the <a href="/doc/articles/defer_panic_recover.html">Defer, Panic, and Recover</a> article for details. 371 </p> 372 373 <h3 id="assertions"> 374 Why does Go not have assertions?</h3> 375 376 <p> 377 Go doesn't provide assertions. They are undeniably convenient, but our 378 experience has been that programmers use them as a crutch to avoid thinking 379 about proper error handling and reporting. Proper error handling means that 380 servers continue operation after non-fatal errors instead of crashing. 381 Proper error reporting means that errors are direct and to the point, 382 saving the programmer from interpreting a large crash trace. Precise 383 errors are particularly important when the programmer seeing the errors is 384 not familiar with the code. 385 </p> 386 387 <p> 388 We understand that this is a point of contention. There are many things in 389 the Go language and libraries that differ from modern practices, simply 390 because we feel it's sometimes worth trying a different approach. 391 </p> 392 393 <h3 id="csp"> 394 Why build concurrency on the ideas of CSP?</h3> 395 <p> 396 Concurrency and multi-threaded programming have a reputation 397 for difficulty. We believe this is due partly to complex 398 designs such as pthreads and partly to overemphasis on low-level details 399 such as mutexes, condition variables, and memory barriers. 400 Higher-level interfaces enable much simpler code, even if there are still 401 mutexes and such under the covers. 402 </p> 403 404 <p> 405 One of the most successful models for providing high-level linguistic support 406 for concurrency comes from Hoare's Communicating Sequential Processes, or CSP. 407 Occam and Erlang are two well known languages that stem from CSP. 408 Go's concurrency primitives derive from a different part of the family tree 409 whose main contribution is the powerful notion of channels as first class objects. 410 Experience with several earlier languages has shown that the CSP model 411 fits well into a procedural language framework. 412 </p> 413 414 <h3 id="goroutines"> 415 Why goroutines instead of threads?</h3> 416 <p> 417 Goroutines are part of making concurrency easy to use. The idea, which has 418 been around for a while, is to multiplex independently executing 419 functions—coroutines—onto a set of threads. 420 When a coroutine blocks, such as by calling a blocking system call, 421 the run-time automatically moves other coroutines on the same operating 422 system thread to a different, runnable thread so they won't be blocked. 423 The programmer sees none of this, which is the point. 424 The result, which we call goroutines, can be very cheap: unless they spend a lot of time 425 in long-running system calls, they cost little more than the memory 426 for the stack, which is just a few kilobytes. 427 </p> 428 429 <p> 430 To make the stacks small, Go's run-time uses segmented stacks. A newly 431 minted goroutine is given a few kilobytes, which is almost always enough. 432 When it isn't, the run-time allocates (and frees) extension segments automatically. 433 The overhead averages about three cheap instructions per function call. 434 It is practical to create hundreds of thousands of goroutines in the same 435 address space. If goroutines were just threads, system resources would 436 run out at a much smaller number. 437 </p> 438 439 <h3 id="atomic_maps"> 440 Why are map operations not defined to be atomic?</h3> 441 442 <p> 443 After long discussion it was decided that the typical use of maps did not require 444 safe access from multiple threads, and in those cases where it did, the map was 445 probably part of some larger data structure or computation that was already 446 synchronized. Therefore requiring that all map operations grab a mutex would slow 447 down most programs and add safety to few. This was not an easy decision, 448 however, since it means uncontrolled map access can crash the program. 449 </p> 450 451 <p> 452 The language does not preclude atomic map updates. When required, such 453 as when hosting an untrusted program, the implementation could interlock 454 map access. 455 </p> 456 457 <h3 id="language_changes"> 458 Will you accept my language change?</h3> 459 460 <p> 461 People often suggest improvements to the language—the 462 <a href="http://groups.google.com/group/golang-nuts">mailing list</a> 463 contains a rich history of such discussions—but very few of these changes have 464 been accepted. 465 </p> 466 467 <p> 468 Although Go is an open source project, the language and libraries are protected 469 by a <a href="/doc/go1compat.html">compatibility promise</a> that prevents 470 changes that break existing programs. 471 If your proposal violates the Go 1 specification we cannot even entertain the 472 idea, regardless of its merit. 473 A future major release of Go may be incompatible with Go 1, but we're not ready 474 to start talking about what that might be. 475 </p> 476 477 <p> 478 Even if your proposal is compatible with the Go 1 spec, it may be 479 not be in the spirit of Go's design goals. 480 The article <i><a href="http://talks.golang.org/2012/splash.article">Go 481 at Google: Language Design in the Service of Software Engineering</a></i> 482 explains Go's origins and the motivation behind its design. 483 </p> 484 485 <h2 id="types">Types</h2> 486 487 <h3 id="Is_Go_an_object-oriented_language"> 488 Is Go an object-oriented language?</h3> 489 490 <p> 491 Yes and no. Although Go has types and methods and allows an 492 object-oriented style of programming, there is no type hierarchy. 493 The concept of “interface” in Go provides a different approach that 494 we believe is easy to use and in some ways more general. There are 495 also ways to embed types in other types to provide something 496 analogous—but not identical—to subclassing. 497 Moreover, methods in Go are more general than in C++ or Java: 498 they can be defined for any sort of data, even built-in types such 499 as plain, “unboxed” integers. 500 They are not restricted to structs (classes). 501 </p> 502 503 <p> 504 Also, the lack of type hierarchy makes “objects” in Go feel much more 505 lightweight than in languages such as C++ or Java. 506 </p> 507 508 <h3 id="How_do_I_get_dynamic_dispatch_of_methods"> 509 How do I get dynamic dispatch of methods?</h3> 510 511 <p> 512 The only way to have dynamically dispatched methods is through an 513 interface. Methods on a struct or any other concrete type are always resolved statically. 514 </p> 515 516 <h3 id="inheritance"> 517 Why is there no type inheritance?</h3> 518 <p> 519 Object-oriented programming, at least in the best-known languages, 520 involves too much discussion of the relationships between types, 521 relationships that often could be derived automatically. Go takes a 522 different approach. 523 </p> 524 525 <p> 526 Rather than requiring the programmer to declare ahead of time that two 527 types are related, in Go a type automatically satisfies any interface 528 that specifies a subset of its methods. Besides reducing the 529 bookkeeping, this approach has real advantages. Types can satisfy 530 many interfaces at once, without the complexities of traditional 531 multiple inheritance. 532 Interfaces can be very lightweight—an interface with 533 one or even zero methods can express a useful concept. 534 Interfaces can be added after the fact if a new idea comes along 535 or for testing—without annotating the original types. 536 Because there are no explicit relationships between types 537 and interfaces, there is no type hierarchy to manage or discuss. 538 </p> 539 540 <p> 541 It's possible to use these ideas to construct something analogous to 542 type-safe Unix pipes. For instance, see how <code>fmt.Fprintf</code> 543 enables formatted printing to any output, not just a file, or how the 544 <code>bufio</code> package can be completely separate from file I/O, 545 or how the <code>image</code> packages generate compressed 546 image files. All these ideas stem from a single interface 547 (<code>io.Writer</code>) representing a single method 548 (<code>Write</code>). And that's only scratching the surface. 549 Go's interfaces have a profound influence on how programs are structured. 550 </p> 551 552 <p> 553 It takes some getting used to but this implicit style of type 554 dependency is one of the most productive things about Go. 555 </p> 556 557 <h3 id="methods_on_basics"> 558 Why is <code>len</code> a function and not a method?</h3> 559 <p> 560 We debated this issue but decided 561 implementing <code>len</code> and friends as functions was fine in practice and 562 didn't complicate questions about the interface (in the Go type sense) 563 of basic types. 564 </p> 565 566 <h3 id="overloading"> 567 Why does Go not support overloading of methods and operators?</h3> 568 <p> 569 Method dispatch is simplified if it doesn't need to do type matching as well. 570 Experience with other languages told us that having a variety of 571 methods with the same name but different signatures was occasionally useful 572 but that it could also be confusing and fragile in practice. Matching only by name 573 and requiring consistency in the types was a major simplifying decision 574 in Go's type system. 575 </p> 576 577 <p> 578 Regarding operator overloading, it seems more a convenience than an absolute 579 requirement. Again, things are simpler without it. 580 </p> 581 582 <h3 id="implements_interface"> 583 Why doesn't Go have "implements" declarations?</h3> 584 585 <p> 586 A Go type satisfies an interface by implementing the methods of that interface, 587 nothing more. This property allows interfaces to be defined and used without 588 having to modify existing code. It enables a kind of structural typing that 589 promotes separation of concerns and improves code re-use, and makes it easier 590 to build on patterns that emerge as the code develops. 591 The semantics of interfaces is one of the main reasons for Go's nimble, 592 lightweight feel. 593 </p> 594 595 <p> 596 See the <a href="#inheritance">question on type inheritance</a> for more detail. 597 </p> 598 599 <h3 id="guarantee_satisfies_interface"> 600 How can I guarantee my type satisfies an interface?</h3> 601 602 <p> 603 You can ask the compiler to check that the type <code>T</code> implements the 604 interface <code>I</code> by attempting an assignment: 605 </p> 606 607 <pre> 608 type T struct{} 609 var _ I = T{} // Verify that T implements I. 610 </pre> 611 612 <p> 613 If <code>T</code> doesn't implement <code>I</code>, the mistake will be caught 614 at compile time. 615 </p> 616 617 <p> 618 If you wish the users of an interface to explicitly declare that they implement 619 it, you can add a method with a descriptive name to the interface's method set. 620 For example: 621 </p> 622 623 <pre> 624 type Fooer interface { 625 Foo() 626 ImplementsFooer() 627 } 628 </pre> 629 630 <p> 631 A type must then implement the <code>ImplementsFooer</code> method to be a 632 <code>Fooer</code>, clearly documenting the fact and announcing it in 633 <a href="/cmd/godoc/">godoc</a>'s output. 634 </p> 635 636 <pre> 637 type Bar struct{} 638 func (b Bar) ImplementsFooer() {} 639 func (b Bar) Foo() {} 640 </pre> 641 642 <p> 643 Most code doesn't make use of such constraints, since they limit the utility of 644 the interface idea. Sometimes, though, they're necessary to resolve ambiguities 645 among similar interfaces. 646 </p> 647 648 <h3 id="t_and_equal_interface"> 649 Why doesn't type T satisfy the Equal interface?</h3> 650 651 <p> 652 Consider this simple interface to represent an object that can compare 653 itself with another value: 654 </p> 655 656 <pre> 657 type Equaler interface { 658 Equal(Equaler) bool 659 } 660 </pre> 661 662 <p> 663 and this type, <code>T</code>: 664 </p> 665 666 <pre> 667 type T int 668 func (t T) Equal(u T) bool { return t == u } // does not satisfy Equaler 669 </pre> 670 671 <p> 672 Unlike the analogous situation in some polymorphic type systems, 673 <code>T</code> does not implement <code>Equaler</code>. 674 The argument type of <code>T.Equal</code> is <code>T</code>, 675 not literally the required type <code>Equaler</code>. 676 </p> 677 678 <p> 679 In Go, the type system does not promote the argument of 680 <code>Equal</code>; that is the programmer's responsibility, as 681 illustrated by the type <code>T2</code>, which does implement 682 <code>Equaler</code>: 683 </p> 684 685 <pre> 686 type T2 int 687 func (t T2) Equal(u Equaler) bool { return t == u.(T2) } // satisfies Equaler 688 </pre> 689 690 <p> 691 Even this isn't like other type systems, though, because in Go <em>any</em> 692 type that satisfies <code>Equaler</code> could be passed as the 693 argument to <code>T2.Equal</code>, and at run time we must 694 check that the argument is of type <code>T2</code>. 695 Some languages arrange to make that guarantee at compile time. 696 </p> 697 698 <p> 699 A related example goes the other way: 700 </p> 701 702 <pre> 703 type Opener interface { 704 Open(name) Reader 705 } 706 707 func (t T3) Open() *os.File 708 </pre> 709 710 <p> 711 In Go, <code>T3</code> does not satisfy <code>Opener</code>, 712 although it might in another language. 713 </p> 714 715 <p> 716 While it is true that Go's type system does less for the programmer 717 in such cases, the lack of subtyping makes the rules about 718 interface satisfaction very easy to state: are the function's names 719 and signatures exactly those of the interface? 720 Go's rule is also easy to implement efficiently. 721 We feel these benefits offset the lack of 722 automatic type promotion. Should Go one day adopt some form of generic 723 typing, we expect there would be a way to express the idea of these 724 examples and also have them be statically checked. 725 </p> 726 727 <h3 id="convert_slice_of_interface"> 728 Can I convert a []T to an []interface{}?</h3> 729 730 <p> 731 Not directly, because they do not have the same representation in memory. 732 It is necessary to copy the elements individually to the destination 733 slice. This example converts a slice of <code>int</code> to a slice of 734 <code>interface{}</code>: 735 </p> 736 737 <pre> 738 t := []int{1, 2, 3, 4} 739 s := make([]interface{}, len(t)) 740 for i, v := range t { 741 s[i] = v 742 } 743 </pre> 744 745 <h3 id="nil_error"> 746 Why is my nil error value not equal to nil? 747 </h3> 748 749 <p> 750 Under the covers, interfaces are implemented as two elements, a type and a value. 751 The value, called the interface's dynamic value, 752 is an arbitrary concrete value and the type is that of the value. 753 For the <code>int</code> value 3, an interface value contains, 754 schematically, (<code>int</code>, <code>3</code>). 755 </p> 756 757 <p> 758 An interface value is <code>nil</code> only if the inner value and type are both unset, 759 (<code>nil</code>, <code>nil</code>). 760 In particular, a <code>nil</code> interface will always hold a <code>nil</code> type. 761 If we store a pointer of type <code>*int</code> inside 762 an interface value, the inner type will be <code>*int</code> regardless of the value of the pointer: 763 (<code>*int</code>, <code>nil</code>). 764 Such an interface value will therefore be non-<code>nil</code> 765 <em>even when the pointer inside is</em> <code>nil</code>. 766 </p> 767 768 <p> 769 This situation can be confusing, and often arises when a <code>nil</code> value is 770 stored inside an interface value such as an <code>error</code> return: 771 </p> 772 773 <pre> 774 func returnsError() error { 775 var p *MyError = nil 776 if bad() { 777 p = ErrBad 778 } 779 return p // Will always return a non-nil error. 780 } 781 </pre> 782 783 <p> 784 If all goes well, the function returns a <code>nil</code> <code>p</code>, 785 so the return value is an <code>error</code> interface 786 value holding (<code>*MyError</code>, <code>nil</code>). 787 This means that if the caller compares the returned error to <code>nil</code>, 788 it will always look as if there was an error even if nothing bad happened. 789 To return a proper <code>nil</code> <code>error</code> to the caller, 790 the function must return an explicit <code>nil</code>: 791 </p> 792 793 794 <pre> 795 func returnsError() error { 796 if bad() { 797 return ErrBad 798 } 799 return nil 800 } 801 </pre> 802 803 <p> 804 It's a good idea for functions 805 that return errors always to use the <code>error</code> type in 806 their signature (as we did above) rather than a concrete type such 807 as <code>*MyError</code>, to help guarantee the error is 808 created correctly. As an example, 809 <a href="/pkg/os/#Open"><code>os.Open</code></a> 810 returns an <code>error</code> even though, if not <code>nil</code>, 811 it's always of concrete type 812 <a href="/pkg/os/#PathError"><code>*os.PathError</code></a>. 813 </p> 814 815 <p> 816 Similar situations to those described here can arise whenever interfaces are used. 817 Just keep in mind that if any concrete value 818 has been stored in the interface, the interface will not be <code>nil</code>. 819 For more information, see 820 <a href="/doc/articles/laws_of_reflection.html">The Laws of Reflection</a>. 821 </p> 822 823 824 <h3 id="unions"> 825 Why are there no untagged unions, as in C?</h3> 826 827 <p> 828 Untagged unions would violate Go's memory safety 829 guarantees. 830 </p> 831 832 <h3 id="variant_types"> 833 Why does Go not have variant types?</h3> 834 835 <p> 836 Variant types, also known as algebraic types, provide a way to specify 837 that a value might take one of a set of other types, but only those 838 types. A common example in systems programming would specify that an 839 error is, say, a network error, a security error or an application 840 error and allow the caller to discriminate the source of the problem 841 by examining the type of the error. Another example is a syntax tree 842 in which each node can be a different type: declaration, statement, 843 assignment and so on. 844 </p> 845 846 <p> 847 We considered adding variant types to Go, but after discussion 848 decided to leave them out because they overlap in confusing ways 849 with interfaces. What would happen if the elements of a variant type 850 were themselves interfaces? 851 </p> 852 853 <p> 854 Also, some of what variant types address is already covered by the 855 language. The error example is easy to express using an interface 856 value to hold the error and a type switch to discriminate cases. The 857 syntax tree example is also doable, although not as elegantly. 858 </p> 859 860 <h2 id="values">Values</h2> 861 862 <h3 id="conversions"> 863 Why does Go not provide implicit numeric conversions?</h3> 864 <p> 865 The convenience of automatic conversion between numeric types in C is 866 outweighed by the confusion it causes. When is an expression unsigned? 867 How big is the value? Does it overflow? Is the result portable, independent 868 of the machine on which it executes? 869 It also complicates the compiler; “the usual arithmetic conversions” 870 are not easy to implement and inconsistent across architectures. 871 For reasons of portability, we decided to make things clear and straightforward 872 at the cost of some explicit conversions in the code. 873 The definition of constants in Go—arbitrary precision values free 874 of signedness and size annotations—ameliorates matters considerably, 875 though. 876 </p> 877 878 <p> 879 A related detail is that, unlike in C, <code>int</code> and <code>int64</code> 880 are distinct types even if <code>int</code> is a 64-bit type. The <code>int</code> 881 type is generic; if you care about how many bits an integer holds, Go 882 encourages you to be explicit. 883 </p> 884 885 <h3 id="builtin_maps"> 886 Why are maps built in?</h3> 887 <p> 888 The same reason strings are: they are such a powerful and important data 889 structure that providing one excellent implementation with syntactic support 890 makes programming more pleasant. We believe that Go's implementation of maps 891 is strong enough that it will serve for the vast majority of uses. 892 If a specific application can benefit from a custom implementation, it's possible 893 to write one but it will not be as convenient syntactically; this seems a reasonable tradeoff. 894 </p> 895 896 <h3 id="map_keys"> 897 Why don't maps allow slices as keys?</h3> 898 <p> 899 Map lookup requires an equality operator, which slices do not implement. 900 They don't implement equality because equality is not well defined on such types; 901 there are multiple considerations involving shallow vs. deep comparison, pointer vs. 902 value comparison, how to deal with recursive types, and so on. 903 We may revisit this issue—and implementing equality for slices 904 will not invalidate any existing programs—but without a clear idea of what 905 equality of slices should mean, it was simpler to leave it out for now. 906 </p> 907 908 <p> 909 In Go 1, unlike prior releases, equality is defined for structs and arrays, so such 910 types can be used as map keys. Slices still do not have a definition of equality, though. 911 </p> 912 913 <h3 id="references"> 914 Why are maps, slices, and channels references while arrays are values?</h3> 915 <p> 916 There's a lot of history on that topic. Early on, maps and channels 917 were syntactically pointers and it was impossible to declare or use a 918 non-pointer instance. Also, we struggled with how arrays should work. 919 Eventually we decided that the strict separation of pointers and 920 values made the language harder to use. Changing these 921 types to act as references to the associated, shared data structures resolved 922 these issues. This change added some regrettable complexity to the 923 language but had a large effect on usability: Go became a more 924 productive, comfortable language when it was introduced. 925 </p> 926 927 <h2 id="Writing_Code">Writing Code</h2> 928 929 <h3 id="How_are_libraries_documented"> 930 How are libraries documented?</h3> 931 932 <p> 933 There is a program, <code>godoc</code>, written in Go, that extracts 934 package documentation from the source code. It can be used on the 935 command line or on the web. An instance is running at 936 <a href="http://golang.org/pkg/">http://golang.org/pkg/</a>. 937 In fact, <code>godoc</code> implements the full site at 938 <a href="http://golang.org/">http://golang.org/</a>. 939 </p> 940 941 <h3 id="Is_there_a_Go_programming_style_guide"> 942 Is there a Go programming style guide?</h3> 943 944 <p> 945 Eventually, there may be a small number of rules to guide things 946 like naming, layout, and file organization. 947 The document <a href="effective_go.html">Effective Go</a> 948 contains some style advice. 949 More directly, the program <code>gofmt</code> is a pretty-printer 950 whose purpose is to enforce layout rules; it replaces the usual 951 compendium of do's and don'ts that allows interpretation. 952 All the Go code in the repository has been run through <code>gofmt</code>. 953 </p> 954 955 <h3 id="How_do_I_submit_patches_to_the_Go_libraries"> 956 How do I submit patches to the Go libraries?</h3> 957 958 <p> 959 The library sources are in <code>go/src/pkg</code>. 960 If you want to make a significant change, please discuss on the mailing list before embarking. 961 </p> 962 963 <p> 964 See the document 965 <a href="contribute.html">Contributing to the Go project</a> 966 for more information about how to proceed. 967 </p> 968 969 <h3 id="Why_does_the_project_use_Mercurial_and_not_git"> 970 Why does the project use Mercurial and not git?</h3> 971 972 <p> 973 The Go project, hosted by Google Code at 974 <a href="http://code.google.com/p/go">code.google.com/p/go</a>, 975 uses Mercurial as its version control system. 976 When the project launched, 977 Google Code supported only Subversion and Mercurial. 978 Mercurial was a better choice because of its plugin mechanism 979 that allowed us to create the "codereview" plugin to connect 980 the project to the excellent code review tools at 981 <a href="http://codereview.appspot.com">codereview.appspot.com</a>. 982 </p> 983 984 <p> 985 Programmers who work 986 with the Go project's source rather than release downloads sometimes 987 ask for the project to switch to git. 988 That would be possible, but it would be a lot of work and 989 would also require reimplementing the codereview plugin. 990 Given that Mercurial works today, with code review support, 991 combined with the Go project's mostly linear, non-branching use of 992 version control, a switch to git doesn't seem worthwhile. 993 </p> 994 995 <h3 id="git_https"> 996 Why does "go get" use HTTPS when cloning a repository?</h3> 997 998 <p> 999 Companies often permit outgoing traffic only on the standard TCP ports 80 (HTTP) 1000 and 443 (HTTPS), blocking outgoing traffic on other ports, including TCP port 9418 1001 (git) and TCP port 22 (SSH). 1002 When using HTTPS instead of HTTP, <code>git</code> enforces certificate validation by 1003 default, providing protection against man-in-the-middle, eavesdropping and tampering attacks. 1004 The <code>go get</code> command therefore uses HTTPS for safety. 1005 </p> 1006 1007 <p> 1008 If you use <code>git</code> and prefer to push changes through SSH using your existing key 1009 it's easy to work around this. For GitHub, try one of these solutions: 1010 </p> 1011 <ul> 1012 <li>Manually clone the repository in the expected package directory: 1013 <pre> 1014 $ cd $GOPATH/src/github.com/username 1015 $ git clone git@github.com:username/package.git 1016 </pre> 1017 </li> 1018 <li>Force <code>git push</code> to use the <code>SSH</code> protocol by appending 1019 these two lines to <code>~/.gitconfig</code>: 1020 <pre> 1021 [url "git@github.com:"] 1022 pushInsteadOf = https://github.com/ 1023 </pre> 1024 </li> 1025 </ul> 1026 1027 <h2 id="Pointers">Pointers and Allocation</h2> 1028 1029 <h3 id="pass_by_value"> 1030 When are function parameters passed by value?</h3> 1031 1032 <p> 1033 As in all languages in the C family, everything in Go is passed by value. 1034 That is, a function always gets a copy of the 1035 thing being passed, as if there were an assignment statement assigning the 1036 value to the parameter. For instance, passing an <code>int</code> value 1037 to a function makes a copy of the <code>int</code>, and passing a pointer 1038 value makes a copy of the pointer, but not the data it points to. 1039 (See the next section for a discussion of how this affects method receivers.) 1040 </p> 1041 1042 <p> 1043 Map and slice values behave like pointers: they are descriptors that 1044 contain pointers to the underlying map or slice data. Copying a map or 1045 slice value doesn't copy the data it points to. Copying an interface value 1046 makes a copy of the thing stored in the interface value. If the interface 1047 value holds a struct, copying the interface value makes a copy of the 1048 struct. If the interface value holds a pointer, copying the interface value 1049 makes a copy of the pointer, but again not the data it points to. 1050 </p> 1051 1052 <h3 id="pointer_to_interface"> 1053 When should I use a pointer to an interface?</h3> 1054 1055 <p> 1056 Almost never. Pointers to interface values arise only in rare, tricky situations involving 1057 disguising an interface value's type for delayed evaluation. 1058 </p> 1059 1060 <p> 1061 It is however a common mistake to pass a pointer to an interface value 1062 to a function expecting an interface. The compiler will complain about this 1063 error but the situation can still be confusing, because sometimes a 1064 <a href="#different_method_sets">pointer 1065 is necessary to satisfy an interface</a>. 1066 The insight is that although a pointer to a concrete type can satisfy 1067 an interface, with one exception <em>a pointer to an interface can never satisfy a interface</em>. 1068 </p> 1069 1070 <p> 1071 Consider the variable declaration, 1072 </p> 1073 1074 <pre> 1075 var w io.Writer 1076 </pre> 1077 1078 <p> 1079 The printing function <code>fmt.Fprintf</code> takes as its first argument 1080 a value that satisfies <code>io.Writer</code>—something that implements 1081 the canonical <code>Write</code> method. Thus we can write 1082 </p> 1083 1084 <pre> 1085 fmt.Fprintf(w, "hello, world\n") 1086 </pre> 1087 1088 <p> 1089 If however we pass the address of <code>w</code>, the program will not compile. 1090 </p> 1091 1092 <pre> 1093 fmt.Fprintf(&w, "hello, world\n") // Compile-time error. 1094 </pre> 1095 1096 <p> 1097 The one exception is that any value, even a pointer to an interface, can be assigned to 1098 a variable of empty interface type (<code>interface{}</code>). 1099 Even so, it's almost certainly a mistake if the value is a pointer to an interface; 1100 the result can be confusing. 1101 </p> 1102 1103 <h3 id="methods_on_values_or_pointers"> 1104 Should I define methods on values or pointers?</h3> 1105 1106 <pre> 1107 func (s *MyStruct) pointerMethod() { } // method on pointer 1108 func (s MyStruct) valueMethod() { } // method on value 1109 </pre> 1110 1111 <p> 1112 For programmers unaccustomed to pointers, the distinction between these 1113 two examples can be confusing, but the situation is actually very simple. 1114 When defining a method on a type, the receiver (<code>s</code> in the above 1115 examples) behaves exactly as if it were an argument to the method. 1116 Whether to define the receiver as a value or as a pointer is the same 1117 question, then, as whether a function argument should be a value or 1118 a pointer. 1119 There are several considerations. 1120 </p> 1121 1122 <p> 1123 First, and most important, does the method need to modify the 1124 receiver? 1125 If it does, the receiver <em>must</em> be a pointer. 1126 (Slices and maps act as references, so their story is a little 1127 more subtle, but for instance to change the length of a slice 1128 in a method the receiver must still be a pointer.) 1129 In the examples above, if <code>pointerMethod</code> modifies 1130 the fields of <code>s</code>, 1131 the caller will see those changes, but <code>valueMethod</code> 1132 is called with a copy of the caller's argument (that's the definition 1133 of passing a value), so changes it makes will be invisible to the caller. 1134 </p> 1135 1136 <p> 1137 By the way, pointer receivers are identical to the situation in Java, 1138 although in Java the pointers are hidden under the covers; it's Go's 1139 value receivers that are unusual. 1140 </p> 1141 1142 <p> 1143 Second is the consideration of efficiency. If the receiver is large, 1144 a big <code>struct</code> for instance, it will be much cheaper to 1145 use a pointer receiver. 1146 </p> 1147 1148 <p> 1149 Next is consistency. If some of the methods of the type must have 1150 pointer receivers, the rest should too, so the method set is 1151 consistent regardless of how the type is used. 1152 See the section on <a href="#different_method_sets">method sets</a> 1153 for details. 1154 </p> 1155 1156 <p> 1157 For types such as basic types, slices, and small <code>structs</code>, 1158 a value receiver is very cheap so unless the semantics of the method 1159 requires a pointer, a value receiver is efficient and clear. 1160 </p> 1161 1162 1163 <h3 id="new_and_make"> 1164 What's the difference between new and make?</h3> 1165 1166 <p> 1167 In short: <code>new</code> allocates memory, <code>make</code> initializes 1168 the slice, map, and channel types. 1169 </p> 1170 1171 <p> 1172 See the <a href="/doc/effective_go.html#allocation_new">relevant section 1173 of Effective Go</a> for more details. 1174 </p> 1175 1176 <h3 id="q_int_sizes"> 1177 What is the size of an <code>int</code> on a 64 bit machine?</h3> 1178 1179 <p> 1180 The sizes of <code>int</code> and <code>uint</code> are implementation-specific 1181 but the same as each other on a given platform. 1182 For portability, code that relies on a particular 1183 size of value should use an explicitly sized type, like <code>int64</code>. 1184 Prior to Go 1.1, the 64-bit Go compilers (both gc and gccgo) used 1185 a 32-bit representation for <code>int</code>. As of Go 1.1 they use 1186 a 64-bit representation. 1187 On the other hand, floating-point scalars and complex 1188 numbers are always sized: <code>float32</code>, <code>complex64</code>, 1189 etc., because programmers should be aware of precision when using 1190 floating-point numbers. 1191 The default size of a floating-point constant is <code>float64</code>. 1192 </p> 1193 1194 <h3 id="stack_or_heap"> 1195 How do I know whether a variable is allocated on the heap or the stack?</h3> 1196 1197 <p> 1198 From a correctness standpoint, you don't need to know. 1199 Each variable in Go exists as long as there are references to it. 1200 The storage location chosen by the implementation is irrelevant to the 1201 semantics of the language. 1202 </p> 1203 1204 <p> 1205 The storage location does have an effect on writing efficient programs. 1206 When possible, the Go compilers will allocate variables that are 1207 local to a function in that function's stack frame. However, if the 1208 compiler cannot prove that the variable is not referenced after the 1209 function returns, then the compiler must allocate the variable on the 1210 garbage-collected heap to avoid dangling pointer errors. 1211 Also, if a local variable is very large, it might make more sense 1212 to store it on the heap rather than the stack. 1213 </p> 1214 1215 <p> 1216 In the current compilers, if a variable has its address taken, that variable 1217 is a candidate for allocation on the heap. However, a basic <em>escape 1218 analysis</em> recognizes some cases when such variables will not 1219 live past the return from the function and can reside on the stack. 1220 </p> 1221 1222 <h3 id="Why_does_my_Go_process_use_so_much_virtual_memory"> 1223 Why does my Go process use so much virtual memory?</h3> 1224 1225 <p> 1226 The Go memory allocator reserves a large region of virtual memory as an arena 1227 for allocations. This virtual memory is local to the specific Go process; the 1228 reservation does not deprive other processes of memory. 1229 </p> 1230 1231 <p> 1232 To find the amount of actual memory allocated to a Go process, use the Unix 1233 <code>top</code> command and consult the <code>RES</code> (Linux) or 1234 <code>RSIZE</code> (Mac OS X) columns. 1235 <!-- TODO(adg): find out how this works on Windows --> 1236 </p> 1237 1238 <h2 id="Concurrency">Concurrency</h2> 1239 1240 <h3 id="What_operations_are_atomic_What_about_mutexes"> 1241 What operations are atomic? What about mutexes?</h3> 1242 1243 <p> 1244 We haven't fully defined it all yet, but some details about atomicity are 1245 available in the <a href="/ref/mem">Go Memory Model specification</a>. 1246 </p> 1247 1248 <p> 1249 Regarding mutexes, the <a href="/pkg/sync">sync</a> 1250 package implements them, but we hope Go programming style will 1251 encourage people to try higher-level techniques. In particular, consider 1252 structuring your program so that only one goroutine at a time is ever 1253 responsible for a particular piece of data. 1254 </p> 1255 1256 <p> 1257 Do not communicate by sharing memory. Instead, share memory by communicating. 1258 </p> 1259 1260 <p> 1261 See the <a href="/doc/codewalk/sharemem/">Share Memory By Communicating</a> code walk and its <a href="http://blog.golang.org/2010/07/share-memory-by-communicating.html">associated article</a> for a detailed discussion of this concept. 1262 </p> 1263 1264 <h3 id="Why_no_multi_CPU"> 1265 Why doesn't my multi-goroutine program use multiple CPUs?</h3> 1266 1267 <p> 1268 You must set the <code>GOMAXPROCS</code> shell environment variable 1269 or use the similarly-named <a href="/pkg/runtime/#GOMAXPROCS"><code>function</code></a> 1270 of the runtime package to allow the 1271 run-time support to utilize more than one OS thread. 1272 </p> 1273 1274 <p> 1275 Programs that perform parallel computation should benefit from an increase in 1276 <code>GOMAXPROCS</code>. 1277 However, be aware that 1278 <a href="http://blog.golang.org/2013/01/concurrency-is-not-parallelism.html">concurrency 1279 is not parallelism</a>. 1280 </p> 1281 1282 <h3 id="Why_GOMAXPROCS"> 1283 Why does using <code>GOMAXPROCS</code> > 1 sometimes make my program 1284 slower?</h3> 1285 1286 <p> 1287 It depends on the nature of your program. 1288 Problems that are intrinsically sequential cannot be sped up by adding 1289 more goroutines. 1290 Concurrency only becomes parallelism when the problem is 1291 intrinsically parallel. 1292 </p> 1293 1294 <p> 1295 In practical terms, programs that spend more time 1296 communicating on channels than doing computation 1297 will experience performance degradation when using 1298 multiple OS threads. 1299 This is because sending data between threads involves switching 1300 contexts, which has significant cost. 1301 For instance, the <a href="/ref/spec#An_example_package">prime sieve example</a> 1302 from the Go specification has no significant parallelism although it launches many 1303 goroutines; increasing <code>GOMAXPROCS</code> is more likely to slow it down than 1304 to speed it up. 1305 </p> 1306 1307 <p> 1308 Go's goroutine scheduler is not as good as it needs to be. In future, it 1309 should recognize such cases and optimize its use of OS threads. For now, 1310 <code>GOMAXPROCS</code> should be set on a per-application basis. 1311 </p> 1312 1313 <p> 1314 For more detail on this topic see the talk entitled, 1315 <a href="http://blog.golang.org/2013/01/concurrency-is-not-parallelism.html">Concurrency 1316 is not Parallelism</a>. 1317 1318 <h2 id="Functions_methods">Functions and Methods</h2> 1319 1320 <h3 id="different_method_sets"> 1321 Why do T and *T have different method sets?</h3> 1322 1323 <p> 1324 From the <a href="/ref/spec#Types">Go Spec</a>: 1325 </p> 1326 1327 <blockquote> 1328 The method set of any other named type <code>T</code> consists of all methods 1329 with receiver type <code>T</code>. The method set of the corresponding pointer 1330 type <code>*T</code> is the set of all methods with receiver <code>*T</code> or 1331 <code>T</code> (that is, it also contains the method set of <code>T</code>). 1332 </blockquote> 1333 1334 <p> 1335 If an interface value contains a pointer <code>*T</code>, 1336 a method call can obtain a value by dereferencing the pointer, 1337 but if an interface value contains a value <code>T</code>, 1338 there is no useful way for a method call to obtain a pointer. 1339 </p> 1340 1341 <p> 1342 Even in cases where the compiler could take the address of a value 1343 to pass to the method, if the method modifies the value the changes 1344 will be lost in the caller. 1345 As a common example, this code: 1346 </p> 1347 1348 <pre> 1349 var buf bytes.Buffer 1350 io.Copy(buf, os.Stdin) 1351 </pre> 1352 1353 <p> 1354 would copy standard input into a <i>copy</i> of <code>buf</code>, 1355 not into <code>buf</code> itself. 1356 This is almost never the desired behavior. 1357 </p> 1358 1359 <h3 id="closures_and_goroutines"> 1360 What happens with closures running as goroutines?</h3> 1361 1362 <p> 1363 Some confusion may arise when using closures with concurrency. 1364 Consider the following program: 1365 </p> 1366 1367 <pre> 1368 func main() { 1369 done := make(chan bool) 1370 1371 values := []string{"a", "b", "c"} 1372 for _, v := range values { 1373 go func() { 1374 fmt.Println(v) 1375 done <- true 1376 }() 1377 } 1378 1379 // wait for all goroutines to complete before exiting 1380 for _ = range values { 1381 <-done 1382 } 1383 } 1384 </pre> 1385 1386 <p> 1387 One might mistakenly expect to see <code>a, b, c</code> as the output. 1388 What you'll probably see instead is <code>c, c, c</code>. This is because 1389 each iteration of the loop uses the same instance of the variable <code>v</code>, so 1390 each closure shares that single variable. When the closure runs, it prints the 1391 value of <code>v</code> at the time <code>fmt.Println</code> is executed, 1392 but <code>v</code> may have been modified since the goroutine was launched. 1393 To help detect this and other problems before they happen, run 1394 <a href="http://golang.org/cmd/go/#hdr-Run_go_tool_vet_on_packages"><code>go vet</code></a>. 1395 </p> 1396 1397 <p> 1398 To bind the current value of <code>v</code> to each closure as it is launched, one 1399 must modify the inner loop to create a new variable each iteration. 1400 One way is to pass the variable as an argument to the closure: 1401 </p> 1402 1403 <pre> 1404 for _, v := range values { 1405 go func(<b>u</b> string) { 1406 fmt.Println(<b>u</b>) 1407 done <- true 1408 }(<b>v</b>) 1409 } 1410 </pre> 1411 1412 <p> 1413 In this example, the value of <code>v</code> is passed as an argument to the 1414 anonymous function. That value is then accessible inside the function as 1415 the variable <code>u</code>. 1416 </p> 1417 1418 <p> 1419 Even easier is just to create a new variable, using a declaration style that may 1420 seem odd but works fine in Go: 1421 </p> 1422 1423 <pre> 1424 for _, v := range values { 1425 <b>v := v</b> // create a new 'v'. 1426 go func() { 1427 fmt.Println(<b>v</b>) 1428 done <- true 1429 }() 1430 } 1431 </pre> 1432 1433 <h2 id="Control_flow">Control flow</h2> 1434 1435 <h3 id="Does_Go_have_a_ternary_form"> 1436 Does Go have the <code>?:</code> operator?</h3> 1437 1438 <p> 1439 There is no ternary form in Go. You may use the following to achieve the same 1440 result: 1441 </p> 1442 1443 <pre> 1444 if expr { 1445 n = trueVal 1446 } else { 1447 n = falseVal 1448 } 1449 </pre> 1450 1451 <h2 id="Packages_Testing">Packages and Testing</h2> 1452 1453 <h3 id="How_do_I_create_a_multifile_package"> 1454 How do I create a multifile package?</h3> 1455 1456 <p> 1457 Put all the source files for the package in a directory by themselves. 1458 Source files can refer to items from different files at will; there is 1459 no need for forward declarations or a header file. 1460 </p> 1461 1462 <p> 1463 Other than being split into multiple files, the package will compile and test 1464 just like a single-file package. 1465 </p> 1466 1467 <h3 id="How_do_I_write_a_unit_test"> 1468 How do I write a unit test?</h3> 1469 1470 <p> 1471 Create a new file ending in <code>_test.go</code> in the same directory 1472 as your package sources. Inside that file, <code>import "testing"</code> 1473 and write functions of the form 1474 </p> 1475 1476 <pre> 1477 func TestFoo(t *testing.T) { 1478 ... 1479 } 1480 </pre> 1481 1482 <p> 1483 Run <code>go test</code> in that directory. 1484 That script finds the <code>Test</code> functions, 1485 builds a test binary, and runs it. 1486 </p> 1487 1488 <p>See the <a href="/doc/code.html">How to Write Go Code</a> document, 1489 the <a href="/pkg/testing/"><code>testing</code></a> package 1490 and the <a href="/cmd/go/#hdr-Test_packages"><code>go test</code></a> subcommand for more details. 1491 </p> 1492 1493 <h3 id="testing_framework"> 1494 Where is my favorite helper function for testing?</h3> 1495 1496 <p> 1497 Go's standard <a href="/pkg/testing/"><code>testing</code></a> package makes it easy to write unit tests, but it lacks 1498 features provided in other language's testing frameworks such as assertion functions. 1499 An <a href="#assertions">earlier section</a> of this document explained why Go 1500 doesn't have assertions, and 1501 the same arguments apply to the use of <code>assert</code> in tests. 1502 Proper error handling means letting other tests run after one has failed, so 1503 that the person debugging the failure gets a complete picture of what is 1504 wrong. It is more useful for a test to report that 1505 <code>isPrime</code> gives the wrong answer for 2, 3, 5, and 7 (or for 1506 2, 4, 8, and 16) than to report that <code>isPrime</code> gives the wrong 1507 answer for 2 and therefore no more tests were run. The programmer who 1508 triggers the test failure may not be familiar with the code that fails. 1509 Time invested writing a good error message now pays off later when the 1510 test breaks. 1511 </p> 1512 1513 <p> 1514 A related point is that testing frameworks tend to develop into mini-languages 1515 of their own, with conditionals and controls and printing mechanisms, 1516 but Go already has all those capabilities; why recreate them? 1517 We'd rather write tests in Go; it's one fewer language to learn and the 1518 approach keeps the tests straightforward and easy to understand. 1519 </p> 1520 1521 <p> 1522 If the amount of extra code required to write 1523 good errors seems repetitive and overwhelming, the test might work better if 1524 table-driven, iterating over a list of inputs and outputs defined 1525 in a data structure (Go has excellent support for data structure literals). 1526 The work to write a good test and good error messages will then be amortized over many 1527 test cases. The standard Go library is full of illustrative examples, such as in 1528 <a href="/src/pkg/fmt/fmt_test.go">the formatting tests for the <code>fmt</code> package</a>. 1529 </p> 1530 1531 1532 <h2 id="Implementation">Implementation</h2> 1533 1534 <h3 id="What_compiler_technology_is_used_to_build_the_compilers"> 1535 What compiler technology is used to build the compilers?</h3> 1536 1537 <p> 1538 <code>Gccgo</code> has a front end written in C++, with a recursive descent parser coupled to the 1539 standard GCC back end. <code>Gc</code> is written in C using 1540 <code>yacc</code>/<code>bison</code> for the parser. 1541 Although it's a new program, it fits in the Plan 9 C compiler suite 1542 (<a href="http://plan9.bell-labs.com/sys/doc/compiler.html">http://plan9.bell-labs.com/sys/doc/compiler.html</a>) 1543 and uses a variant of the Plan 9 loader to generate ELF/Mach-O/PE binaries. 1544 </p> 1545 1546 <p> 1547 We considered writing <code>gc</code>, the original Go compiler, in Go itself but 1548 elected not to do so because of the difficulties of bootstrapping and 1549 especially of open source distribution—you'd need a Go compiler to 1550 set up a Go environment. <code>Gccgo</code>, which came later, makes it possible to 1551 consider writing a compiler in Go, which might well happen. 1552 (Go would be a 1553 fine language in which to implement a compiler; a native lexer and 1554 parser are already available in the <a href="/pkg/go/"><code>go</code></a> package 1555 and a type checker is in the works.) 1556 </p> 1557 1558 <p> 1559 We also considered using LLVM for <code>gc</code> but we felt it was too large and 1560 slow to meet our performance goals. 1561 </p> 1562 1563 <h3 id="How_is_the_run_time_support_implemented"> 1564 How is the run-time support implemented?</h3> 1565 1566 <p> 1567 Again due to bootstrapping issues, the run-time code is mostly in C (with a 1568 tiny bit of assembler) although Go is capable of implementing most of 1569 it now. <code>Gccgo</code>'s run-time support uses <code>glibc</code>. 1570 <code>Gc</code> uses a custom library to keep the footprint under 1571 control; it is 1572 compiled with a version of the Plan 9 C compiler that supports 1573 segmented stacks for goroutines. 1574 The <code>gccgo</code> compiler implements segmented 1575 stacks on Linux only, supported by recent modifications to the gold linker. 1576 </p> 1577 1578 <h3 id="Why_is_my_trivial_program_such_a_large_binary"> 1579 Why is my trivial program such a large binary?</h3> 1580 1581 <p> 1582 The linkers in the gc tool chain (<code>5l</code>, <code>6l</code>, and <code>8l</code>) 1583 do static linking. All Go binaries therefore include the Go 1584 run-time, along with the run-time type information necessary to support dynamic 1585 type checks, reflection, and even panic-time stack traces. 1586 </p> 1587 1588 <p> 1589 A simple C "hello, world" program compiled and linked statically using gcc 1590 on Linux is around 750 kB, 1591 including an implementation of <code>printf</code>. 1592 An equivalent Go program using <code>fmt.Printf</code> 1593 is around 1.2 MB, but 1594 that includes more powerful run-time support. 1595 </p> 1596 1597 <h3 id="unused_variables_and_imports"> 1598 Can I stop these complaints about my unused variable/import?</h3> 1599 1600 <p> 1601 The presence of an unused variable may indicate a bug, while 1602 unused imports just slow down compilation. 1603 Accumulate enough unused imports in your code tree and 1604 things can get very slow. 1605 For these reasons, Go allows neither. 1606 </p> 1607 1608 <p> 1609 When developing code, it's common to create these situations 1610 temporarily and it can be annoying to have to edit them out before the 1611 program will compile. 1612 </p> 1613 1614 <p> 1615 Some have asked for a compiler option to turn those checks off 1616 or at least reduce them to warnings. 1617 Such an option has not been added, though, 1618 because compiler options should not affect the semantics of the 1619 language and because the Go compiler does not report warnings, only 1620 errors that prevent compilation. 1621 </p> 1622 1623 <p> 1624 There are two reasons for having no warnings. First, if it's worth 1625 complaining about, it's worth fixing in the code. (And if it's not 1626 worth fixing, it's not worth mentioning.) Second, having the compiler 1627 generate warnings encourages the implementation to warn about weak 1628 cases that can make compilation noisy, masking real errors that 1629 <em>should</em> be fixed. 1630 </p> 1631 1632 <p> 1633 It's easy to address the situation, though. Use the blank identifier 1634 to let unused things persist while you're developing. 1635 </p> 1636 1637 <pre> 1638 import "unused" 1639 1640 // This declaration marks the import as used by referencing an 1641 // item from the package. 1642 var _ = unused.Item // TODO: Delete before committing! 1643 1644 func main() { 1645 debugData := debug.Profile() 1646 _ = debugData // Used only during debugging. 1647 .... 1648 } 1649 </pre> 1650 1651 <h2 id="Performance">Performance</h2> 1652 1653 <h3 id="Why_does_Go_perform_badly_on_benchmark_x"> 1654 Why does Go perform badly on benchmark X?</h3> 1655 1656 <p> 1657 One of Go's design goals is to approach the performance of C for comparable 1658 programs, yet on some benchmarks it does quite poorly, including several 1659 in <a href="/test/bench/shootout/">test/bench/shootout</a>. The slowest depend on libraries 1660 for which versions of comparable performance are not available in Go. 1661 For instance, <a href="/test/bench/shootout/pidigits.go">pidigits.go</a> 1662 depends on a multi-precision math package, and the C 1663 versions, unlike Go's, use <a href="http://gmplib.org/">GMP</a> (which is 1664 written in optimized assembler). 1665 Benchmarks that depend on regular expressions 1666 (<a href="/test/bench/shootout/regex-dna.go">regex-dna.go</a>, for instance) are 1667 essentially comparing Go's native <a href="/pkg/regexp">regexp package</a> to 1668 mature, highly optimized regular expression libraries like PCRE. 1669 </p> 1670 1671 <p> 1672 Benchmark games are won by extensive tuning and the Go versions of most 1673 of the benchmarks need attention. If you measure comparable C 1674 and Go programs 1675 (<a href="/test/bench/shootout/reverse-complement.go">reverse-complement.go</a> is one example), you'll see the two 1676 languages are much closer in raw performance than this suite would 1677 indicate. 1678 </p> 1679 1680 <p> 1681 Still, there is room for improvement. The compilers are good but could be 1682 better, many libraries need major performance work, and the garbage collector 1683 isn't fast enough yet. (Even if it were, taking care not to generate unnecessary 1684 garbage can have a huge effect.) 1685 </p> 1686 1687 <p> 1688 In any case, Go can often be very competitive. 1689 There has been significant improvement in the performance of many programs 1690 as the language and tools have developed. 1691 See the blog post about 1692 <a href="http://blog.golang.org/2011/06/profiling-go-programs.html">profiling 1693 Go programs</a> for an informative example. 1694 1695 <h2 id="change_from_c">Changes from C</h2> 1696 1697 <h3 id="different_syntax"> 1698 Why is the syntax so different from C?</h3> 1699 <p> 1700 Other than declaration syntax, the differences are not major and stem 1701 from two desires. First, the syntax should feel light, without too 1702 many mandatory keywords, repetition, or arcana. Second, the language 1703 has been designed to be easy to analyze 1704 and can be parsed without a symbol table. This makes it much easier 1705 to build tools such as debuggers, dependency analyzers, automated 1706 documentation extractors, IDE plug-ins, and so on. C and its 1707 descendants are notoriously difficult in this regard. 1708 </p> 1709 1710 <h3 id="declarations_backwards"> 1711 Why are declarations backwards?</h3> 1712 <p> 1713 They're only backwards if you're used to C. In C, the notion is that a 1714 variable is declared like an expression denoting its type, which is a 1715 nice idea, but the type and expression grammars don't mix very well and 1716 the results can be confusing; consider function pointers. Go mostly 1717 separates expression and type syntax and that simplifies things (using 1718 prefix <code>*</code> for pointers is an exception that proves the rule). In C, 1719 the declaration 1720 </p> 1721 <pre> 1722 int* a, b; 1723 </pre> 1724 <p> 1725 declares <code>a</code> to be a pointer but not <code>b</code>; in Go 1726 </p> 1727 <pre> 1728 var a, b *int 1729 </pre> 1730 <p> 1731 declares both to be pointers. This is clearer and more regular. 1732 Also, the <code>:=</code> short declaration form argues that a full variable 1733 declaration should present the same order as <code>:=</code> so 1734 </p> 1735 <pre> 1736 var a uint64 = 1 1737 </pre> 1738 <p> 1739 has the same effect as 1740 </p> 1741 <pre> 1742 a := uint64(1) 1743 </pre> 1744 <p> 1745 Parsing is also simplified by having a distinct grammar for types that 1746 is not just the expression grammar; keywords such as <code>func</code> 1747 and <code>chan</code> keep things clear. 1748 </p> 1749 1750 <p> 1751 See the article about 1752 <a href="/doc/articles/gos_declaration_syntax.html">Go's Declaration Syntax</a> 1753 for more details. 1754 </p> 1755 1756 <h3 id="no_pointer_arithmetic"> 1757 Why is there no pointer arithmetic?</h3> 1758 <p> 1759 Safety. Without pointer arithmetic it's possible to create a 1760 language that can never derive an illegal address that succeeds 1761 incorrectly. Compiler and hardware technology have advanced to the 1762 point where a loop using array indices can be as efficient as a loop 1763 using pointer arithmetic. Also, the lack of pointer arithmetic can 1764 simplify the implementation of the garbage collector. 1765 </p> 1766 1767 <h3 id="inc_dec"> 1768 Why are <code>++</code> and <code>--</code> statements and not expressions? And why postfix, not prefix?</h3> 1769 <p> 1770 Without pointer arithmetic, the convenience value of pre- and postfix 1771 increment operators drops. By removing them from the expression 1772 hierarchy altogether, expression syntax is simplified and the messy 1773 issues around order of evaluation of <code>++</code> and <code>--</code> 1774 (consider <code>f(i++)</code> and <code>p[i] = q[++i]</code>) 1775 are eliminated as well. The simplification is 1776 significant. As for postfix vs. prefix, either would work fine but 1777 the postfix version is more traditional; insistence on prefix arose 1778 with the STL, a library for a language whose name contains, ironically, a 1779 postfix increment. 1780 </p> 1781 1782 <h3 id="semicolons"> 1783 Why are there braces but no semicolons? And why can't I put the opening 1784 brace on the next line?</h3> 1785 <p> 1786 Go uses brace brackets for statement grouping, a syntax familiar to 1787 programmers who have worked with any language in the C family. 1788 Semicolons, however, are for parsers, not for people, and we wanted to 1789 eliminate them as much as possible. To achieve this goal, Go borrows 1790 a trick from BCPL: the semicolons that separate statements are in the 1791 formal grammar but are injected automatically, without lookahead, by 1792 the lexer at the end of any line that could be the end of a statement. 1793 This works very well in practice but has the effect that it forces a 1794 brace style. For instance, the opening brace of a function cannot 1795 appear on a line by itself. 1796 </p> 1797 1798 <p> 1799 Some have argued that the lexer should do lookahead to permit the 1800 brace to live on the next line. We disagree. Since Go code is meant 1801 to be formatted automatically by 1802 <a href="/cmd/gofmt/"><code>gofmt</code></a>, 1803 <i>some</i> style must be chosen. That style may differ from what 1804 you've used in C or Java, but Go is a new language and 1805 <code>gofmt</code>'s style is as good as any other. More 1806 important—much more important—the advantages of a single, 1807 programmatically mandated format for all Go programs greatly outweigh 1808 any perceived disadvantages of the particular style. 1809 Note too that Go's style means that an interactive implementation of 1810 Go can use the standard syntax one line at a time without special rules. 1811 </p> 1812 1813 <h3 id="garbage_collection"> 1814 Why do garbage collection? Won't it be too expensive?</h3> 1815 <p> 1816 One of the biggest sources of bookkeeping in systems programs is 1817 memory management. We feel it's critical to eliminate that 1818 programmer overhead, and advances in garbage collection 1819 technology in the last few years give us confidence that we can 1820 implement it with low enough overhead and no significant 1821 latency. 1822 </p> 1823 1824 <p> 1825 Another point is that a large part of the difficulty of concurrent 1826 and multi-threaded programming is memory management; 1827 as objects get passed among threads it becomes cumbersome 1828 to guarantee they become freed safely. 1829 Automatic garbage collection makes concurrent code far easier to write. 1830 Of course, implementing garbage collection in a concurrent environment is 1831 itself a challenge, but meeting it once rather than in every 1832 program helps everyone. 1833 </p> 1834 1835 <p> 1836 Finally, concurrency aside, garbage collection makes interfaces 1837 simpler because they don't need to specify how memory is managed across them. 1838 </p> 1839 1840 <p> 1841 The current implementation is a parallel mark-and-sweep 1842 collector but a future version might take a different approach. 1843 </p> 1844 1845 <p> 1846 On the topic of performance, keep in mind that Go gives the programmer 1847 considerable control over memory layout and allocation, much more than 1848 is typical in garbage-collected languages. A careful programmer can reduce 1849 the garbage collection overhead dramatically by using the language well; 1850 see the article about 1851 <a href="http://blog.golang.org/2011/06/profiling-go-programs.html">profiling 1852 Go programs</a> for a worked example, including a demonstration of Go's 1853 profiling tools. 1854 </p>