go_faq.html 88 KB

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