1
0

go_faq.html 75 KB

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