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