Jump to content

Go (programming language): Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
UTF8 strings are in C11
m v2.05b - Bot T20 CW#61 - Fix errors for CW project (Reference before punctuation)
 
Line 1: Line 1:
{{short description|Programming language}}
<br />
{{Distinguish2|[[Go! (programming language)]], an agent-based language released in 2003}}
{{for|the 2003 agent-based programming language|Go! (programming language)}}
{{lead too short|date=March 2012}}
{{Use American English|date=August 2022}}
{{Use mdy dates|date=October 2018}}
{{Infobox programming language
{{Infobox programming language
| name = Go
| name = Go
| logo = [[Image:golang.png]]
| logo = [[File:Go Logo Blue.svg|frameless|220x80px]]
| logo size = 128px
| caption =
| logo caption =
| paradigm = [[compiled language|compiled]], [[concurrent programming|concurrent]], [[imperative programming|imperative]], [[structured programming|structured]]
| paradigm = [[Multi-paradigm programming language|Multi-paradigm]]: [[concurrent programming|concurrent]] [[imperative programming|imperative]], [[functional programming|functional]]<ref>{{Cite web |url=https://go.dev/doc/codewalk/functions/ |title=Codewalk: First-Class Functions in Go |quote=Go supports first class functions, higher-order functions, user-defined function types, function literals, closures, and multiple return values. This rich feature set supports a functional programming style in a strongly typed language.}}</ref> [[object-oriented programming|object-oriented]]<ref>{{Cite web |url=https://golang.org/doc/faq#Is_Go_an_object-oriented_language |title=Is Go an object-oriented language? |access-date=April 13, 2019 |quote=Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy.}}</ref><ref>{{Cite web |url=https://talks.golang.org/2012/chat.slide#5 |title=Go: code that grows with grace |access-date=June 24, 2018 |quote=Go is Object Oriented, but not in the usual way.}}</ref>
| year = 2009
| year = {{start date and age|2009|11|10}}
| designer = Robert Griesemer<br />[[Rob Pike]]<br />[[Ken Thompson]]
| designer = [[Robert Griesemer]]<br />[[Rob Pike]]<br />[[Ken Thompson]]<ref name="langfaq" />
| developer = [[Google|Google Inc.]]
| developer = The Go Authors<ref name="license" />
| latest_release_version = version 1.0.3<ref>{{cite mailing list |url=https://groups.google.com/forum/#!topic/golang-announce/co3SvXbGrNk |title=go1.0.3 released |date=24 September 2012 |accessdate=05 October 2012 |last=Gerrand |first=Andrew |mailinglist=golang-announce |publisher=Google}}</ref>
| latest release version = {{#statements:software version identifier}}
| latest_release_date = {{start date and age|df=yes|2012|09|24}}
| latest release date = {{start date and age|{{wikidata|qualifier|single|P348|P577}}}}
| latest_test_version =
| latest_test_version =
| latest_test_date =
| latest_test_date = <!--{{start date and age|2016|08|08}}<ref name="preview_page">{{Cite web |url=https://golang.org/dl/ |title=Release History |website=The Go Programming Language |access-date=August 8, 2016}}</ref>-->
| typing = [[strong typing|strong]], [[static typing|static]]
| typing = [[type inference|Inferred]], [[static typing|static]], [[strong typing|strong]],<ref>{{cite web | url=https://go.dev/ref/spec#Introduction | title=The Go Programming Language Specification - the Go Programming Language }}</ref> [[structural typing|structural]],<ref name="structural_typing">{{Cite web |url=https://golang.org/doc/faq#implements_interface |title=Why doesn't Go have "implements" declarations? |website=The Go Programming Language |access-date=October 1, 2015}}</ref><ref>{{Cite web |url=https://twitter.com/rob_pike/status/546973312543227904 |title=Rob Pike on Twitter |last=Pike |first=Rob |date=December 22, 2014 |access-date=March 13, 2016 |quote=Go has structural typing, not duck typing. Full interface satisfaction is checked and required. |url-status=dead |archive-url=https://web.archive.org/web/20220407025913/https://twitter.com/rob_pike/status/546973312543227904 |archive-date=2022-04-07}}</ref> [[nominal typing|nominal]]
| implementations = gc (8g, 6g, 5g), gccgo
| memory management = [[Garbage collection (computer science)|Garbage collection]]
| dialects =
| implementations = gc, gofrontend
| influenced_by = [[C (programming language)|C]], [[Limbo (programming language)|Limbo]], [[Modula]], [[Newsqueak]], [[Oberon (programming language)|Oberon]], [[Pascal (programming language)|Pascal]],<ref name="langfaq"/> [[Python (programming language)|Python]]
| programming language = Go, [[Assembly language]] (gc); [[C++]] (gofrontend)
| operating_system = [[Linux]], [[Mac OS X]], [[FreeBSD]], [[OpenBSD]], [[Microsoft Windows|MS Windows]], [[Plan 9 from Bell Labs|Plan 9]]<ref>{{cite web|url=http://go-lang.cat-v.org/os-ports|title=Go Porting Efforts|date=12 January 2010|work=Go Language Resources|publisher=cat-v|accessdate=18 January 2010}}</ref>
| dialects =
| license = [[BSD licenses|BSD]]-style<ref>{{cite web |url=http://golang.org/LICENSE |title=Text file LICENSE |work=The Go Programming Language |publisher=Google |accessdate=05 October 2012}}</ref> + Patent grant<ref>{{cite web |url=http://code.google.com/p/go/source/browse/PATENTS |title=Additional IP Rights Grant |last= |first= |date= |work=The Go Programming Language |publisher=Google |accessdate=05 October 2012}}</ref>
| influenced_by = {{#statements:influenced by}}
| website = {{URL|http://golang.org}}
| influenced = [[Crystal (programming language)|Crystal]], [[V (programming language)|V]]
| file_ext = .go
| operating_system = [[DragonFly BSD]], [[FreeBSD]], [[Linux]], [[macOS]], [[NetBSD]], [[OpenBSD]],<ref name="openbsd">{{Cite web |url=http://ports.su/lang/go |title=lang/go: go-1.4 |date=December 23, 2014 |website=OpenBSD ports |access-date=January 19, 2015}}</ref> [[Plan 9 from Bell Labs|Plan 9]],<ref>{{Cite web |url=http://go-lang.cat-v.org/os-ports |title=Go Porting Efforts |date=January 12, 2010 |website=Go Language Resources |publisher=cat-v |access-date=January 18, 2010}}</ref> [[Solaris (operating system)|Solaris]], [[Windows]]
| license = [[3-clause BSD]]<ref name="license">{{Cite web |url=http://golang.org/LICENSE |title=Text file LICENSE |website=The Go Programming Language |access-date=October 5, 2012}}</ref> + [[software patents|patent]] grant<ref>{{Cite web |url=http://golang.org/PATENTS |title=Additional IP Rights Grant |website=The Go Programming Language |access-date=October 5, 2012}}</ref>
| file_ext = .go
}}
}}
'''Go''' is a fast<ref>{{Cite web |title=Go Introduction |url=https://www.w3schools.com/go/go_introduction.php |access-date=2024-11-23 |website=www.w3schools.com |language=en-US}}</ref> [[static typing|statically typed]], [[compiled language|compiled]] [[high-level programming language|high-level]] [[general purpose programming language]]. It is known for its simplicity and efficiency.<ref>{{Cite web |title=Go Introduction |url=https://www.w3schools.com/go/go_introduction.php |access-date=2024-11-23 |website=www.w3schools.com |language=en-US}}</ref> Its simplicity express through its basic syntax of the language itself and its large library that help the developer to have a small stack for its project. It was designed at [[Google]]<ref name="techcrunch">{{Cite news |last=Kincaid |first=Jason |date=November 10, 2009 |title=Google's Go: A New Programming Language That's Python Meets C++ |language=en-US |work=TechCrunch |url=https://techcrunch.com/2009/11/10/google-go-language/ |access-date=January 18, 2010}}</ref> in 2009 by [[Robert Griesemer]], [[Rob Pike]], and [[Ken Thompson]].<ref name="langfaq">{{Cite web |date=January 16, 2010 |title=Language Design FAQ |url=http://golang.org/doc/go_faq.html |access-date=February 27, 2010 |website=The Go Programming Language |language=en-US}}</ref> It is [[syntax (programming languages)|syntactically]] similar to [[C (programming language)|C]], but also has [[memory safety]], [[garbage collection (computer science)|garbage collection]], [[structural type system|structural typing]],<ref name="structural_typing" /> and [[communicating sequential processes|CSP]]-style [[concurrency (computer science)|concurrency]].<ref name="boldly">{{Cite web |url=https://www.theregister.co.uk/2011/05/05/google_go/ |title=Google Go boldly goes where no code has gone before |last=Metz |first=Cade |date=May 5, 2011 |website=The Register}}</ref> It is often referred to as '''Golang''' because of its former domain name, <code>golang.org</code>, but its proper name is Go.<ref>{{Cite web |url=https://go.dev/doc/faq#go_or_golang |title=Is the language called Go or Golang? |access-date=March 16, 2022 |quote=The language is called Go.}}</ref>


There are two major implementations:
'''Go''' is a [[compiled language|compiled]], [[Garbage collection (computer science)|garbage-collected]], [[concurrent programming language|concurrent]] [[programming language]] developed by [[Google|Google Inc.]]<ref>{{cite news|url=http://www.techcrunch.com/2009/11/10/google-go-language/|title=Google’s Go: A New Programming Language That’s Python Meets C++|last=Kincaid |first=Jason |date=10 November 2009 |newspaper=TechCrunch |accessdate=18 January 2010}}</ref>


* The original, [[Self-hosting (compilers)|self-hosting]]<ref>{{Cite web |url=https://golang.org/doc/go1.5#implementation |title=Go 1.5 Release Notes |access-date=January 28, 2016 |quote=The compiler and runtime are now implemented in Go and assembler, without C.}}</ref> [[compiler]] [[toolchain]], initially developed inside Google;<ref>{{Cite web |url=https://github.com/golang/go |title=The Go programming language |access-date=2024-11-01}}</ref>
The initial design of Go was started in September 2007 by [[Robert Griesemer]], [[Rob Pike]], and [[Ken Thompson]].<ref name="langfaq">{{cite web|url=http://golang.org/doc/go_faq.html|title=Language Design FAQ|date=16 January 2010|work=golang.org|accessdate=27 February 2010}}</ref> Go was officially announced in November 2009. In May 2010, Rob Pike publicly stated that Go was being used "for real stuff" at Google.<ref name="register">{{cite news| url = http://www.theregister.co.uk/2010/05/20/go_in_production_at_google/ | title = Google programming Frankenstein is a Go | newspaper = [[The Register]] | date = 20 May 2010 |first=Cade |last=Metz}}</ref> Go's "gc" compiler targets the [[Linux]], [[Mac OS X]], [[FreeBSD]], [[OpenBSD]], [[Plan 9 from Bell Labs|Plan 9]], and [[Microsoft Windows]] operating systems and the [[i386]], [[amd64]], and [[ARM]] processor architectures.<ref>{{cite web|url=http://golang.org/doc/install.html#tmp_33|title=Installing Go|date=11 June 2010|work=golang.org|publisher=The Go Authors|accessdate=11 June 2010}}</ref>
* A frontend written in [[C++]], called gofrontend,<ref>{{Cite web |url=https://github.com/golang/gofrontend |title=gofrontend |access-date=2024-11-01}}</ref> originally a [[GNU Compiler Collection|GCC]] frontend, providing gccgo, a GCC-based Go compiler;<ref>{{Cite web |url=https://gcc.gnu.org/onlinedocs/gcc-14.2.0/gccgo/ |title=gccgo |access-date=2024-11-01 |quote=gccgo, the GNU compiler for the Go programming language}}</ref> later extended to also support [[LLVM]], providing an LLVM-based Go compiler called gollvm.<ref>{{Cite web |url=https://go.googlesource.com/gollvm/ |title=Gollvm |access-date=2024-11-01 |quote=Gollvm is an LLVM-based Go compiler.}}</ref>


A third-party [[source-to-source compiler]], GopherJS,<ref>{{Cite web | url=https://github.com/gopherjs/gopherjs | title=A compiler from Go to JavaScript for running Go code in a browser: Gopherjs/Gopherjs| website=[[GitHub]] |url-status=live |archive-url=https://web.archive.org/web/20231212143621/https://github.com/gopherjs/gopherjs |archive-date= Dec 12, 2023 }}</ref> compiles Go to [[JavaScript]] for [[front-end web development]].
==Goals==
{{toclimit}}
Go aims to provide the efficiency of a [[statically typed]] compiled language with the ease of programming of a [[Dynamic programming language|dynamic language]].<ref name=go_lang_video_2009>{{cite web|last=Pike|first=Rob|title=The Go Programming Language|url=http://www.youtube.com/watch?v=rKnDgT73v8s&feature=related|publisher=YouTube|accessdate=1 Jul 2011}}</ref> Other goals include:


==History==
* Safety: [[Type-safe]] and [[Memory safety|memory-safe]].
Go was designed at [[Google]] in 2007 to improve [[programming productivity]] in an era of [[multi-core processor|multicore]], [[computer network|networked]] [[computer|machines]] and large [[codebase]]s.<ref>{{Cite web |url=https://talks.golang.org/2012/splash.article |title=Go at Google: Language Design in the Service of Software Engineering |access-date=October 8, 2018}}</ref> The designers wanted to address criticisms of other languages in use at Google, but keep their useful characteristics:<ref>{{Cite web |url=http://www.stanford.edu/class/ee380/Abstracts/100428.html |title=Another Go at Language Design |last=Pike |first=Rob |date=April 28, 2010 |website=Stanford EE Computer Systems Colloquium |publisher=[[Stanford University]]}} [https://www.youtube.com/watch?v=7VcArS4Wpqk Video available].</ref>
* Good support for concurrency and communication.
* [[Static typing]] and [[Run time (program lifecycle phase)|run-time]] efficiency (like [[C (programming language)|C]])
* Efficient, latency-free garbage collection.
* [[Readability]] and [[usability]] (like [[Python (programming language)|Python]])<ref>{{Cite web |url=https://golang.org/doc/faq#different_syntax |title=Frequently Asked Questions (FAQ) - The Go Programming Language |website=The Go Programming Language |access-date=February 26, 2016}}</ref>
* High-speed compilation.
* High-performance [[computer network|networking]] and [[multiprocessing]]


Its designers were primarily motivated by their shared [[Criticism of C++|dislike of C++]].<ref>{{Cite web|archive-url=https://web.archive.org/web/20130105013259/https://www.drdobbs.com/open-source/interview-with-ken-thompson/229502480|archive-date=January 5, 2013 | url=http://www.drdobbs.com/open-source/interview-with-ken-thompson/229502480 |title=Dr. Dobb's: Interview with Ken Thompson |last= Binstock |first=Andrew|date=May 18, 2011 |access-date=February 7, 2014}}</ref><ref>{{Cite web |url=http://commandcenter.blogspot.mx/2012/06/less-is-exponentially-more.html |title=Less is exponentially more |last=Pike |first=Rob |year=2012}}</ref><ref>{{Cite web |url=https://talks.golang.org/2015/gophercon-goevolution.slide#4 |title=The Evolution of Go |last= Griesemer |first=Robert|year=2015}}</ref>
==Description==


Go was publicly announced in November 2009,<ref>{{Cite web |url=https://opensource.googleblog.com/2009/11/hey-ho-lets-go.html |title=Hey! Ho! Let's Go! |last1=Griesemer |first1=Robert |last2=Pike |first2=Rob |website=Google Open Source |access-date=May 17, 2018 |last3=Thompson |first3=Ken |last4=Taylor |first4=Ian |last5=Cox |first5=Russ |last6=Kim |first6=Jini |last7=Langley |first7=Adam}}</ref> and version 1.0 was released in March 2012.<ref>{{Cite news |last=Shankland |first=Stephen |url=https://www.cnet.com/news/googles-go-language-turns-one-wins-a-spot-at-youtube/ |title=Google's Go language turns one, wins a spot at YouTube: The lower-level programming language has matured enough to sport the 1.0 version number. And it's being used for real work at Google. |date=March 30, 2012 |access-date=August 6, 2017 |publisher=CBS Interactive Inc |department=News |quote=Google has released version 1 of its Go programming language, an ambitious attempt to improve upon giants of the lower-level programming world such as C and C++. |website=CNet}}</ref><ref>{{Cite web|url=https://golang.org/doc/devel/release.html|title=Release History |website=The Go Programming Language}}</ref> Go is widely used in production at Google<ref name="faq">{{Cite news |url=https://golang.org/doc/faq#internal_usage |title=Go FAQ: Is Google using Go internally? |access-date=March 9, 2013}}</ref> and in many other organizations and open-source projects.
The [[Syntax (programming languages)|syntax]] of Go is broadly similar to that of [[C (programming language)|C]]: blocks of code are surrounded with [[curly brace]]s; common [[control flow]] structures include <code>[[for loop|for]]</code>, <code>[[switch statement|switch]]</code>, and <code>[[conditional (programming)|if]]</code>. Unlike C, line-ending semicolons are optional, variable declarations are written differently and are usually optional, type conversions must be made explicitly, and new <code>go</code> and <code>select</code> control keywords have been introduced to support concurrent programming. New built-in types include [[map (data structure)|maps]], array slices, and channels for inter-thread communication.


===Branding and styling===
Go is designed for exceptionally fast compiling times, even on modest hardware.<ref name="techtalk-compiling">{{cite video |people= [[Rob Pike]] |date= 10 November 2009 |title= The Go Programming Language |url= http://www.youtube.com/watch?v=rKnDgT73v8s#t=8m53 |format= flv |medium= Tech talk |publisher= Google |time= 8:53}}</ref> The language requires [[Garbage collection (computer science)|garbage collection]]. Certain concurrency-related structural conventions of Go ([[channel (programming)|channel]]s and alternative channel inputs) are borrowed from [[C. A. R. Hoare|Tony Hoare's]] [[Communicating sequential processes|CSP]]. Unlike previous concurrent programming languages such as [[Occam (programming language)|occam]] or [[Limbo (programming language)|Limbo]], Go does not provide any built-in notion of safe or verifiable concurrency.<ref name="memmodel">{{cite web| url = http://golang.org/doc/go_mem.html | title = The Go Memory Model | publisher = Google | accessdate =5 January 2011}}</ref>
[[File:Golang.png|thumb|Mascot of Go programming language is a [[Gopher]] shown above.]]


The [[Gopher]] [[mascot]] was introduced in 2009 for the [[open source]] launch of the language. The design, by [[Renée French]], borrowed from a c. 2000 [[WFMU]] promotion.<ref>{{cite web |title=The Go Gopher - The Go Programming Language |url=https://go.dev/blog/gopher |website=go.dev |access-date=2023-02-09 |language=en}}</ref>
Of features found in C++ or Java, Go does not include [[inheritance (object-oriented programming)|type inheritance]], [[generic programming]], [[Assertion (computing)|assertions]], [[method overloading]], or [[pointer arithmetic]].<ref name="langfaq"/> Of these, the Go authors express an openness to generic programming, explicitly argue against assertions and pointer arithmetic, while defending the choice to omit type inheritance as giving a more useful language, encouraging heavy use of [[Protocol (object-oriented programming)|interfaces]] instead.<ref name="langfaq"/> Initially, the language did not include [[exception handling]], but in March 2010 a mechanism known as <code>panic</code>/<code>recover</code> was implemented to handle exceptional errors while avoiding some of the problems the Go authors find with exceptions.<ref>[http://golang.org/doc/devel/weekly.html#2010-03-30 Release notes, 30 March 2010]</ref><ref>{{cite web|url=http://groups.google.com/group/golang-nuts/browse_thread/thread/1ce5cd050bb973e4|title=Proposal for an exception-like mechanism |date=25 March 2010|work=golang-nuts|accessdate=25 March 2010}}</ref>


In November 2016, the Go and Go Mono fonts were released by type designers [[Charles Bigelow (type designer)|Charles Bigelow]] and [[Kris Holmes]] specifically for use by the Go project. Go is a [[humanist sans-serif]] resembling [[Lucida Grande]], and Go Mono is [[monospaced]]. Both fonts adhere to the [[WGL4]] character set and were designed to be legible with a large [[x-height]] and distinct [[letterform]]s. Both Go and Go Mono adhere to the [[DIN]] 1450 standard by having a slashed zero, lowercase <code>l</code> with a tail, and an uppercase <code>I</code> with serifs.<ref>{{Cite web |url=https://blog.golang.org/go-fonts |title=Go fonts |date=16 November 2016 |publisher=Go |access-date=12 March 2019}}</ref><ref>{{Cite web |url=https://github.com/golang/image/tree/master/font/gofont/ttfs |title=Go Font TTFs |website=GitHub |access-date=April 2, 2019}}</ref>
==Type system==


In April 2018, the original logo was redesigned by brand designer Adam Smith. The new logo is a modern, stylized GO slanting right with trailing streamlines. (The Gopher mascot remained the same.<ref>{{Cite web |url=https://blog.golang.org/go-brand |title=Go's New Brand |website=The Go Blog |access-date=2018-11-09}}</ref>)
Go allows a programmer to write functions that can operate on inputs of arbitrary type, provided that the type implements the functions defined by a given interface.


===Generics===
Unlike [[Java (programming language)|Java]], the interfaces a type supports do not need to be specified at the point at which the type is defined, and Go interfaces do not participate in a type hierarchy. A Go interface is best described as a set of methods, each identified by a name and signature. A type is considered to implement an interface if all the required methods have been defined for that type. An interface can be declared to "embed" other interfaces, meaning the declared interface includes the methods defined in the other interfaces.<ref name="memmodel">{{cite web| url = http://golang.org/doc/effective_go.html#interfaces_and_types | title = Effective Go - Interfaces and methods & Embedding | publisher = Google | accessdate =28 November 2011}}</ref>
The lack of support for [[generic programming]] in initial versions of Go drew considerable criticism.<ref>{{cite web | url=https://go.dev/blog/survey2020-results#:~:text=Among%20the%2026%25%20of%20respondents%20who%20said%20Go%20lacks%20language%20features%20they%20need%2C%2088%25%20selected%20generics%20as%20a%20critical%20missing%20feature. | title=Go Developer Survey 2020 Results | last=Merrick | first=Alice | website=Go Programming Language | date=March 9, 2021 | access-date=March 16, 2022}}</ref> The designers expressed an openness to generic programming and noted that built-in functions ''were'' in fact type-generic, but are treated as special cases; Pike called this a weakness that might be changed at some point.<ref name="append">{{cite web |title=Arrays, slices (and strings): The mechanics of 'append' |first=Rob |last=Pike |website=The Go Blog |url=http://blog.golang.org/slices |date=September 26, 2013 |access-date=March 7, 2015}}</ref> The Google team built at least one compiler for an experimental Go dialect with generics, but did not release it.<ref>{{cite web |title=E2E: Erik Meijer and Robert Griesemer |website=Channel 9 |publisher=Microsoft |date=May 7, 2012 |url=http://channel9.msdn.com/Blogs/Charles/Erik-Meijer-and-Robert-Griesemer-Go}}</ref>


In August 2018, the Go principal contributors published draft designs for generic programming and [[exception handling|error handling]] and asked users to submit feedback.<ref>{{Cite web |url=https://go.googlesource.com/proposal/+/master/design/go2draft.md |title=Go 2 Draft Designs |access-date=September 12, 2018}}</ref><ref>{{Cite web |url=https://blog.golang.org/go2draft |title=The Go Blog: Go 2 Draft Designs |date=August 28, 2018}}</ref> However, the error handling proposal was eventually abandoned.<ref>{{cite web |url=https://github.com/golang/go/issues/32437 |title=Proposal: A built-in Go error check function, "try" |website=Go repository on GitHub |access-date=March 16, 2022}}</ref>
Unlike Java, the in-memory representation of an object does not contain a pointer to a [[virtual method table]]. Instead a value of interface type is implemented as a pair of a pointer to the object, and a pointer to a dictionary containing implementations of the interface methods for that type.<ref>{{cite web|url = http://research.swtch.com/interfaces | title = Go Data Structures: Interfaces | accessdate=15 November 2012}}</ref>


In June 2020, a new draft design document<ref>{{cite web |url=https://go.googlesource.com/proposal/+/refs/heads/master/design/go2draft-type-parameters.md |title= Type Parameters&nbsp;— Draft Design |work=go.googlesource.com}}</ref> was published that would add the necessary syntax to Go for declaring generic functions and types. A code translation tool, ''{{mono|go2go}}'', was provided to allow users to try the new syntax, along with a generics-enabled version of the online Go Playground.<ref>{{cite web |url=https://bitfieldconsulting.com/golang/generics |title= Generics in Go |work=bitfieldconsulting.com|date= December 17, 2021 }}</ref>
Consider the following example:

Generics were finally added to Go in version 1.18 on March 15, 2022.<ref>{{cite web |url=https://go.dev/blog/go1.18 |title=Go 1.18 is released! |website=Go Programming Language |date=March 15, 2022 |access-date=March 16, 2022}}</ref>

===Versioning===
Go 1 guarantees compatibility<ref>{{Cite web|url=https://golang.org/doc/go1compat|title=Go 1 and the Future of Go Programs |website=The Go Programming Language}}</ref> for the language specification and major parts of the standard library. All versions up through the current Go 1.23 release<ref>{{Cite web|title=Go 1.23 Release Notes|url=https://go.dev/doc/go1.23|website=The Go Programming Language}}</ref> have maintained this promise.

Go does not follow [[SemVer]]; rather, each major Go release is supported until there are two newer major releases. Unlike most software, Go calls the second number in a version the major, i.e., in <code>1.x</code> <code>x</code> is the major version. <ref>{{Cite web|url=https://golang.org/doc/devel/release.html#policy|title=Release History|website=The Go Programming Language}}</ref> This is because Go plans to never reach 2.0, given that compatibility is one of language's major selling points.<ref>{{Cite web|url=https://go.dev/blog/compat|title=Backward Compatibility, Go 1.21, and Go 2|website=The Go Programming Language}}</ref>

==Design==
Go is influenced by [[C (programming language)|C]] (especially the [[Plan 9 from Bell Labs|Plan 9]] [[Dialect (computing)|dialect]]<ref>{{Cite web|title=A Quick Guide to Go's Assembler |url=https://go.dev/doc/asm|access-date=2021-12-31|website=go.dev}}</ref>{{Failed verification|date=June 2022|talk=Plan 9 C}}), but with an emphasis on greater simplicity and safety. It consists of:
* A syntax and environment adopting patterns more common in [[dynamic programming language|dynamic language]]s:<ref name="go_lang_video_2009">{{Cite web |url=https://www.youtube.com/watch?v=rKnDgT73v8s |title=The Go Programming Language |last=Pike |first=Rob |publisher=YouTube |access-date=July 1, 2011}}</ref>
** Optional concise variable declaration and initialization through [[type inference]] (<syntaxhighlight lang="Go" inline>x := 0</syntaxhighlight> instead of <syntaxhighlight lang="Go" inline>var x int = 0;</syntaxhighlight> or <syntaxhighlight lang="Go" inline>var x = 0;</syntaxhighlight>)
** Fast compilation<ref name="techtalk-compiling">{{Cite AV media |url=https://www.youtube.com/watch?v=rKnDgT73v8s#t=8m53 |title=The Go Programming Language |date=November 10, 2009 |last= Pike |first=Rob|publisher=Google |time=8:53 |format=flv |medium=Tech talk}}</ref>
** Remote package management (<code>go get</code>)<ref>{{cite web|url=http://golang.org/cmd/go/#hdr-Download_and_install_packages_and_dependencies|title=Download and install packages and dependencies }} See [http://godoc.org godoc.org] for addresses and documentation of some packages.</ref> and online package documentation<ref>{{Cite web |url=http://godoc.org |title=GoDoc |website=godoc.org}}</ref>
* Distinctive approaches to particular problems:
** Built-in concurrency primitives: [[light-weight process]]es (goroutines), [[channel (programming)|channels]], and the <code>select</code> statement
** An [[protocol (object-oriented programming)|interface]] system in place of [[virtual inheritance]], and type embedding instead of non-virtual inheritance
** A toolchain that, by default, produces [[static library|statically linked]] native binaries without external Go dependencies
* A desire to keep the language specification simple enough to hold in a programmer's head,<ref>{{cite web|last=Pike|first=Rob|url=http://5by5.tv/changelog/100|title=The Changelog|type=Podcast|access-date=October 7, 2013|archive-date=October 20, 2013|archive-url=https://web.archive.org/web/20131020101046/http://5by5.tv/changelog/100|url-status=dead}}</ref> in part by [[#Omissions|omitting features that are common in similar languages]].

===Syntax===
Go's syntax includes changes from [[C (programming language)|C]] aimed at keeping code concise and readable. A combined declaration/initialization operator was introduced that allows the programmer to write <syntaxhighlight lang="Go" inline>i := 3</syntaxhighlight> or <syntaxhighlight lang="Go" inline>s := "Hello, world!"</syntaxhighlight>, [[type inference|without specifying the types]] of variables used. This contrasts with C's <syntaxhighlight lang="C" inline>int i = 3;</syntaxhighlight> and <syntaxhighlight lang="C" inline>const char *s = "Hello, world!";</syntaxhighlight>.

Semicolons still terminate statements;{{efn|But "To allow complex statements to occupy a single line, a semicolon may be omitted before a closing ) or }".<ref>{{Cite web |url=https://golang.org/ref/spec#Semicolons |title=Go Programming Language Specification, §Semicolons |website=The Go Programming Language}}</ref>}} but are implicit when the end of a line occurs.{{efn|"if the newline comes after a token that could end a statement, [the lexer will] insert a semicolon".<ref>{{Cite web |url=https://golang.org/doc/effective_go.html#semicolons |title=Effective Go, §Semicolons |website=The Go Programming Language}}</ref>}}

Methods may return multiple values, and returning a <syntaxhighlight lang="Go" inline="">result, err</syntaxhighlight> pair is the conventional way a method indicates an error to its caller in Go.{{efn|Usually, exactly one of the result and error values has a value other than the type's zero value; sometimes both do, as when a read or write can only be partially completed, and sometimes neither, as when a read returns 0 bytes. See [[Semipredicate problem#Multivalued return|Semipredicate problem: Multivalued return]].}} Go adds literal syntaxes for initializing struct parameters by name and for initializing [[Associative array|maps]] and [[Array slicing|slices]]. As an alternative to C's three-statement <code>for</code> loop, Go's <code>range</code> expressions allow concise iteration over arrays, slices, strings, maps, and channels.<ref>{{Cite web|url=https://golang.org/ref/spec#For_statements|title=The Go Programming Language Specification |website=The Go Programming Language}}</ref>

<code>fmt.Println("Hello World!")</code> is a statement.

In Go, statements are separated by ending a line (hitting the Enter key) or by a semicolon "<code>;</code>".

Hitting the Enter key adds "<code>;</code>" to the end of the line implicitly (does not show up in the source code).

The left curly bracket <code>{</code> cannot come at the start of a line.<ref>{{Cite web |title=Go Syntax |url=https://www.w3schools.com/go/go_syntax.php |access-date=2024-11-23 |website=www.w3schools.com |language=en-US}}</ref>

===Types===
Go has a number of built-in types, including numeric ones ({{mono|byte}}, {{mono|int64}}, {{mono|float32}}, etc.), [[Boolean data type|Booleans]], and byte strings ({{mono|string}}). Strings are immutable; built-in operators and keywords (rather than functions) provide concatenation, comparison, and [[UTF-8]] encoding/decoding.<ref>{{cite web|last=Pike|first=Rob|url=http://blog.golang.org/strings|title=Strings, bytes, runes and characters in Go|date=October 23, 2013}}</ref> [[Record (computer science)|Record types]] can be defined with the {{mono|struct}} keyword.<ref>{{Cite web |url=https://www.golang-book.com/books/intro/9 |title=Structs and Interfaces&nbsp;— An Introduction to Programming in Go |last=Doxsey |first=Caleb |website=www.golang-book.com |access-date=15 October 2018}}</ref>

For each type {{mono|''T''}} and each non-negative integer constant {{mono|''n''}}, there is an [[array data type|array type]] denoted {{mono|[''n'']''T''}}; arrays of differing lengths are thus of different types. [[Dynamic array]]s are available as "slices", denoted {{mono|[]''T''}} for some type {{mono|''T''}}. These have a length and a ''capacity'' specifying when new memory needs to be allocated to expand the array. Several slices may share their underlying memory.{{r|append}}<ref>{{cite web|last=Gerrand|first=Andrew|url=http://blog.golang.org/go-slices-usage-and-internals|title=Go Slices: usage and internals}}</ref><ref>{{cite web|author=The Go Authors|url=http://golang.org/doc/effective_go.html#slices|title=Effective Go: Slices}}</ref>

[[Pointer (computer programming)|''Pointers'']] are available for all types, and the pointer-to-{{mono|''T''}} type is denoted {{mono|*''T''}}. Address-taking and indirection use the {{mono|&amp;}} and {{mono|*}} operators, as in C, or happen implicitly through the method call or attribute access syntax.<ref>{{cite web|author=The Go authors|url=https://golang.org/ref/spec#Selectors|title=Selectors }}</ref><ref>{{cite web|author=The Go authors|url=https://golang.org/ref/spec#Calls|title=Calls }}</ref> There is no pointer arithmetic,{{efn|name=noPointerArith}} except via the special {{mono|unsafe.Pointer}} type in the standard library.<ref>{{Cite web |url=https://golang.org/ref/spec#Package_unsafe |title=Go Programming Language Specification, §Package unsafe |website=The Go Programming Language}}</ref>

For a pair of types {{mono|''K''}}, {{mono|''V''}}, the type {{mono|map[''K'']''V''}} is the type mapping type-{{mono|''K''}} keys to type-{{mono|''V''}} values, though Go Programming Language specification does not give any performance guarantees or implementation requirements for map types. Hash tables are built into the language, with special syntax and built-in functions. {{mono|chan '' T''}} is a ''channel'' that allows sending values of type ''T'' between [[#Concurrency|concurrent Go processes]].<ref>{{Cite web|title=The Go Programming Language Specification |url=https://go.dev/ref/spec#Channel_types|access-date=2021-12-31|website=go.dev}}</ref>

Aside from its support for [[#Interfaces|interfaces]], Go's type system is [[nominal type system|nominal]]: the {{mono|type}} keyword can be used to define a new ''named type'', which is distinct from other named types that have the same layout (in the case of a {{mono|struct}}, the same members in the same order). Some conversions between types (e.g., between the various integer types) are pre-defined and adding a new type may define additional conversions, but conversions between named types must always be invoked explicitly.<ref>{{Cite web |url=http://golang.org/ref/spec#Assignability |title=The Go Programming Language Specification |website=The Go Programming Language}}</ref> For example, the {{mono|type}} keyword can be used to define a type for [[IPv4]] addresses, based on 32-bit unsigned integers as follows:


<syntaxhighlight lang="go">
<syntaxhighlight lang="go">
type Sequence []int
type ipv4addr uint32
</syntaxhighlight>


With this type definition, {{mono|ipv4addr(x)}} interprets the {{mono|uint32}} value {{mono|x}} as an IP address. Simply assigning {{mono|x}} to a variable of type {{mono|ipv4addr}} is a type error.<ref>{{Cite web |url=https://go.dev/tour/basics/13|title=A tour of go |website=go.dev}}</ref>
func (s Sequence) Len() int {

return len(s)
''Constant expressions'' may be either typed or "untyped"; they are given a type when assigned to a typed variable if the value they represent passes a compile-time check.<ref>{{Cite web |url=http://golang.org/ref/spec#Constants |title=The Go Programming Language Specification |website=The Go Programming Language}}</ref>

''[[Subroutine|Function]] types'' are indicated by the {{mono|func}} keyword; they take zero or more [[parameter (computer programming)|parameters]] and [[return statement|return]] zero or more values, all of which are typed. The parameter and return values determine a function type; thus, {{mono|func(string, int32) (int, error)}} is the type of functions that take a {{mono|string}} and a 32-bit signed integer, and return a signed integer (of default width) and a value of the built-in interface type {{mono|error}}.<ref>{{Cite web|title=The Go Programming Language Specification |url=https://go.dev/ref/spec#Function_types|access-date=2021-12-31|website=go.dev}}</ref>

Any named type has a [[method (computer programming)|method]] set associated with it. The IP address example above can be extended with a method for checking whether its value is a known standard:

<syntaxhighlight lang="go">
// ZeroBroadcast reports whether addr is 255.255.255.255.
func (addr ipv4addr) ZeroBroadcast() bool {
return addr == 0xFFFFFFFF
}
}
</syntaxhighlight>


Due to nominal typing, this method definition adds a method to {{mono|ipv4addr}}, but not on {{mono|uint32}}. While methods have special definition and call syntax, there is no distinct method type.<ref>{{Cite web |url=http://golang.org/ref/spec#Calls |title=The Go Programming Language Specification |website=The Go Programming Language}}</ref>
type HasLength interface {

Len() int
===={{anchor|Interfaces}} Interface system====
Go provides two features that replace [[inheritance (object-oriented programming)|class inheritance]].{{citation needed|date=December 2016}}

The first is ''embedding'', which can be viewed as an automated form of [[object composition|composition]].{{r|gohotdraw}}

The second are its ''[[protocol (object-oriented programming)|interface]]s'', which provides [[runtime polymorphism]].<ref name="balbaert">{{Cite book |last=Balbaert |first=Ivo |title=The Way to Go: A Thorough Introduction to the Go Programming Language |publisher=iUniverse |year=2012}}</ref>{{rp|266}} Interfaces are a class of types and provide a limited form of [[structural type system|structural typing]] in the otherwise nominal type system of Go. An object which is of an interface type is also of another type, much like [[C++]] objects being simultaneously of a base and derived class. The design of Go interfaces was inspired by [[protocol (object-oriented programming)|protocol]]s from the Smalltalk programming language.<ref>{{Cite web |url=https://talks.golang.org/2015/gophercon-goevolution.slide#19 |title=The Evolution of Go |website=talks.golang.org |access-date=March 13, 2016}}</ref> Multiple sources use the term [[duck typing]] when describing Go interfaces.<ref>{{Cite web|last=Diggins|first=Christopher|date=November 24, 2009|title=Duck Typing and the Go Programming Language|url=http://www.drdobbs.com/architecture-and-design/duck-typing-and-the-go-programming-langu/228701527|access-date=March 10, 2016|website=Dr. Dobb's, The world of software development}}</ref><ref>{{Cite web |url=https://medium.com/@matryer/golang-advent-calendar-day-one-duck-typing-a513aaed544d#.ebm7j81xu |title=Duck typing in Go |last=Ryer |first=Mat |date=December 1, 2015 |access-date=March 10, 2016}}</ref> Although the term duck typing is not precisely defined and therefore not wrong, it usually implies that type conformance is not statically checked. Because conformance to a Go interface is checked statically by the Go compiler (except when performing a type assertion), the Go authors prefer the term ''structural typing''.<ref>{{Cite web |url=https://golang.org/doc/faq |title=Frequently Asked Questions (FAQ) - The Go Programming Language |website=The Go Programming Language}}</ref>

The definition of an interface type lists required methods by name and type. Any object of type T for which functions exist matching all the required methods of interface type I is an object of type I as well. The definition of type T need not (and cannot) identify type I. For example, if {{mono|Shape}}, {{mono|Square}} {{mono|and Circle}} are defined as

<syntaxhighlight lang="go">
import "math"

type Shape interface {
Area() float64
}
}


type Square struct { // Note: no "implements" declaration
func Foo (o HasLength) {
...
side float64
}
}

func (sq Square) Area() float64 { return sq.side * sq.side }

type Circle struct { // No "implements" declaration here either
radius float64
}

func (c Circle) Area() float64 { return math.Pi * math.Pow(c.radius, 2) }
</syntaxhighlight>
</syntaxhighlight>


then both a {{mono|Square}} and a {{mono|Circle}} are implicitly a {{mono|Shape}} and can be assigned to a {{mono|Shape}}-typed variable.{{r|balbaert}}{{rp|263–268}} In formal language, Go's interface system provides [[structural type system|structural]] rather than [[nominal type system|nominal]] typing. Interfaces can embed other interfaces with the effect of creating a combined interface that is satisfied by exactly the types that implement the embedded interface and any methods that the newly defined interface adds.{{r|balbaert}}{{rp|270}}
These four definitions could have been placed in separate files, in different parts of the program. Notably, the programmer who defined the <code>Sequence</code> type did not need to declare that the type implemented <code>HasLength</code>, and the person who implemented the <code>Len</code> method for <code>Sequence</code> did not need to specify that this method was part of <code>HasLength</code>.


The Go standard library uses interfaces to provide genericity in several places, including the input/output system that is based on the concepts of {{mono|Reader}} and {{mono|Writer}}.{{r|balbaert}}{{rp|282–283}}
==Name visibility==


Besides calling methods via interfaces, Go allows converting interface values to other types with a run-time type check. The language constructs to do so are the ''type assertion'',<ref>{{Cite web |url=http://golang.org/ref/spec#Type_assertions |title=The Go Programming Language Specification |website=The Go Programming Language}}</ref> which checks against a single potential type:<syntaxhighlight lang="go">
[[Linkage (software)|Visibility]] of structures, structure fields, variables, constants, methods, top-level types and functions outside their defining package is defined implicitly according to the capitalization of their identifier.<ref>{{cite web|url=http://golang.org/doc/go_tutorial.html|title=A Tutorial for the Go Programming Language|work=The Go Programming Language|publisher=Google|accessdate=10 March 2010|quote=In Go the rule about visibility of information is simple: if a name (of a top-level type, function, method, constant or variable, or of a structure field or method) is capitalized, users of the package may see it. Otherwise, the name and hence the thing being named is visible only inside the package in which it is declared.}}</ref>
var shp Shape = Square{5}
square, ok := shp.(Square) // Asserts Square type on shp, should work
if ok {
fmt.Printf("%#v\n", square)
} else {
fmt.Println("Can't print shape as Square")
}
</syntaxhighlight>and the ''type switch'',<ref>{{Cite web |url=http://golang.org/ref/spec#Type_switches |title=The Go Programming Language Specification |website=The Go Programming Language}}</ref> which checks against multiple types:{{citation needed|date=December 2016}}<syntaxhighlight lang="go">
func (sq Square) Diagonal() float64 { return sq.side * math.Sqrt2 }
func (c Circle) Diameter() float64 { return 2 * c.radius }


func LongestContainedLine(shp Shape) float64 {
==Concurrency==
switch v := shp.(type) {
Go provides ''goroutines'', small lightweight threads; the name alludes to [[coroutine]]s. Goroutines are created with the <code>go</code> statement from anonymous or named functions.
case Square:
return v.Diagonal() // Or, with type assertion, shp.(Square).Diagonal()
case Circle:
return v.Diameter() // Or, with type assertion, shp.(Circle).Diameter()
default:
return 0 // In practice, this should be handled with errors
}
}
</syntaxhighlight>The ''empty interface'' <syntaxhighlight lang="Go" inline>interface{}</syntaxhighlight> is an important base case because it can refer to an item of ''any'' concrete type. It is similar to the {{mono|Object}} class in [[Java (programming language)|Java]] or [[C Sharp (programming language)|C#]] and is satisfied by any type, including built-in types like {{mono|int}}.{{r|balbaert}}{{rp|284}} Code using the empty interface cannot simply call methods (or built-in operators) on the referred-to object, but it can store the <syntaxhighlight lang="Go" inline>interface{}</syntaxhighlight> value, try to convert it to a more useful type via a type assertion or type switch, or inspect it with Go's <code>reflect</code> package.<ref>{{Cite web|url=https://pkg.go.dev/reflect|title=reflect package |website=pkg.go.dev}}</ref> Because <syntaxhighlight lang="Go" inline>interface{}</syntaxhighlight> can refer to any value, it is a limited way to escape the restrictions of static typing, like <syntaxhighlight lang="C" inline>void*</syntaxhighlight> in C but with additional run-time type checks.{{citation needed|date=December 2016}}


The <syntaxhighlight lang="Go" inline>interface{}</syntaxhighlight> type can be used to model structured data of any arbitrary schema in Go, such as [[JSON]] or [[YAML]] data, by representing it as a <syntaxhighlight lang="Go" inline>map[string]interface{}</syntaxhighlight> (map of string to empty interface). This recursively describes data in the form of a dictionary with string keys and values of any type.<ref>{{cite web |url=https://bitfieldconsulting.com/golang/map-string-interface |title= map[string]interface{} in Go |work=bitfieldconsulting.com|date= June 6, 2020 }}</ref>
Goroutines are executed in parallel with other goroutines, including their caller. They do not necessarily run in separate threads, but a group of goroutines are multiplexed onto multiple threads — execution control is moved between them by blocking them when sending or receiving messages over channels.


Interface values are implemented using pointer to data and a second pointer to run-time type information.<ref>{{Cite web |url=http://research.swtch.com/interfaces |title=Go Data Structures: Interfaces |access-date=November 15, 2012}}</ref> Like some other types implemented using pointers in Go, interface values are <code>nil</code> if uninitialized.<ref>{{Cite web |url=http://golang.org/ref/spec#Interface_types |title=The Go Programming Language Specification |website=The Go Programming Language}}</ref>
==Implementations==


====Generic code using parameterized types====
There are currently two Go compilers:
Since version 1.18, Go supports generic code using parameterized types.<ref>{{cite web |url=https://go.dev/doc/go1.18#generics |title=Go 1.18 Release Notes: Generics |website=Go Programming Language |date=March 15, 2022 |access-date=March 16, 2022}}</ref>
* 6g/8g/5g (the compilers for AMD64, x86, and ARM respectively) with their supporting tools (collectively known as "gc") based on Thompson's previous work on [[Plan 9 from Bell Labs|Plan 9]]'s C toolchain.
* gccgo, a [[GNU Compiler Collection|GCC]] frontend written in C++,<ref>{{cite web|url=http://golang.org/doc/go_faq.html#Implementation|title=FAQ: Implementation|date=16 January 2010|work=golang.org|accessdate=18 January 2010}}</ref> and now officially supported as of version 4.6, albeit not part of the standard binary for gcc.<ref>{{cite web | url=http://gcc.gnu.org/install/configure.html | title=Installing GCC: Configuration | accessdate=3 December 2011 | quote=Ada, Go and Objective-C++ are not default languages}}</ref>


Functions and types now have the ability to be generic using type parameters. These type parameters are specified within square brackets, right after the function or type name.<ref>{{Cite web |title=Type Parameters Proposal |url=https://go.googlesource.com/proposal/+/HEAD/design/43651-type-parameters.md |access-date=2023-06-25 |website=go.googlesource.com}}</ref> The compiler transforms the generic function or type into non-generic by substituting ''type arguments'' for the type parameters provided, either explicitly by the user or type inference by the compiler.<ref>{{Cite web |title=The Go Programming Language Specification - The Go Programming Language |url=https://go.dev/ref/spec |access-date=2023-06-25 |website=go.dev |language=en}}</ref> This transformation process is referred to as type instantiation.<ref>{{Cite web |title=An Introduction To Generics - The Go Programming Language |url=https://go.dev/blog/intro-generics |access-date=2023-06-25 |website=go.dev |language=en}}</ref>
Both compilers work on Unix-like systems, and a port to Microsoft Windows of the gc compiler and runtime have been integrated in the main distribution. Most of the standard libraries also work on Windows.
Interfaces now can define a set of types (known as type set) using <code>|</code> (Union) operator, as well as a set of methods. These changes were made to support type constraints in generics code. For a generic function or type, a constraint can be thought of as the type of the type argument: a meta-type. This new <code>~T</code> syntax will be the first use of <code>~</code> as a token in Go. <code>~T</code> means the set of all types whose underlying type is <code>T</code>.<ref>{{Cite web |title=Type Parameters Proposal |url=https://go.googlesource.com/proposal/+/HEAD/design/43651-type-parameters.md#using-a-constraint |access-date=2023-06-25 |website=go.googlesource.com}}</ref><syntaxhighlight lang="go">
type Number interface {
~int | ~float64 | ~float32 | ~int32 | ~int64
}


func Add[T Number](nums ...T) T {
There is also an unmaintained "tiny" runtime environment that allows Go programs to run on bare hardware.<ref>{{cite web|url=http://groups.google.com/group/golang-nuts/browse_thread/thread/b877e34723b543a7|title=release.2011-02-01|last=Gerrand|first=Andrew|date=1 February 2011|work=golang-nuts|publisher=[[Google]]|accessdate=5 February 2011}}</ref>
var sum T
for _, v := range nums {
sum += v
}
return sum
}


func main() {
==Examples==
add := Add[int] // Type instantiation
println(add(1, 2, 3, 4, 5)) // 15


res := Add(1.1, 2.2, 3.3, 4.4, 5.5) // Type Inference
===Hello world===
println(res) // +1.650000e+001
}
</syntaxhighlight>


====Enumerated types====
The following is a [[Hello world program]] in Go:
{{excerpt|Enumerated type|Go|subsections=yes}}


===Package system===
In Go's package system, each package has a path (e.g., <code>"compress/bzip2"</code> or <code>"golang.org/x/net/html"</code>) and a name (e.g., <code>bzip2</code> or <code>html</code>). References to other packages' definitions must ''always'' be prefixed with the other package's name, and only the ''capitalized'' names from other packages are accessible: <code>io.Reader</code> is public but <code>bzip2.reader</code> is not.<ref>{{Cite web |url=http://golang.org/doc/go_tutorial.html |title=A Tutorial for the Go Programming Language |website=The Go Programming Language |access-date=March 10, 2013 |quote=In Go the rule about visibility of information is simple: if a name (of a top-level type, function, method, constant or variable, or of a structure field or method) is capitalized, users of the package may see it. Otherwise, the name and hence the thing being named is visible only inside the package in which it is declared.}}</ref> The <code>go get</code> command can retrieve packages stored in a remote repository<ref>{{Cite web |url=http://golang.org/cmd/go/#hdr-Download_and_install_packages_and_dependencies |title=go |website=The Go Programming Language}}</ref> and developers are encouraged to develop packages inside a base path corresponding to a source repository (such as example.com/user_name/package_name) to reduce the likelihood of name collision with future additions to the standard library or other external libraries.<ref>{{Cite web |url=https://golang.org/doc/code.html |title=How to Write Go Code |website=The Go Programming Language |quote=The packages from the standard library are given short import paths such as "fmt" and "net/http". For your own packages, you must choose a base path that is unlikely to collide with future additions to the standard library or other external libraries. If you keep your code in a source repository somewhere, then you should use the root of that source repository as your base path. For instance, if you have an Example account at example.com/user, that should be your base path}}</ref>

==={{anchor|Concurrency}} Concurrency: goroutines and channels===
The Go language has built-in facilities, as well as library support, for writing [[concurrent programming|concurrent programs]]. Concurrency refers not only to CPU parallelism, but also to [[asynchronous I/O|asynchrony]]: letting slow operations like a database or network read run while the program does other work, as is common in event-based servers.<ref name="concurrency-is-not">{{cite web|last=Pike |first=Rob |url=http://vimeo.com/49718712 |title=Concurrency is not Parallelism|date=September 18, 2012 }}</ref>

The primary concurrency construct is the ''goroutine'', a type of [[green thread]].<ref name=":0">{{Cite book |last1=Donovan |first1=Alan A. A. |title=The Go programming language |last2=Kernighan |first2=Brian W. |date=2016 |publisher=Addison-Wesley |isbn=978-0-13-419044-0 |series=Addison-Wesley professional computing series |location=New York, Munich |pages=}}</ref>{{Rp|pages=280-281}} A function call prefixed with the <code>go</code> keyword starts a function in a new goroutine. The language specification does not specify how goroutines should be implemented, but current implementations multiplex a Go process's goroutines onto a smaller set of [[thread (computer science)|operating-system threads]], similar to the scheduling performed in [[Erlang (programming language)|Erlang]].{{r|phrasebook}}{{rp|10}}

While a standard library package featuring most of the classical [[concurrency control]] structures ([[mutex]] locks, etc.) is available,{{r|phrasebook}}{{rp|151–152}} idiomatic concurrent programs instead prefer ''channels'', which [[message passing|send messages]] between goroutines.<ref>{{Cite web |url=http://golang.org/doc/effective_go.html#sharing |title=Effective Go |website=The Go Programming Language}}</ref> Optional buffers store messages in [[FIFO (computing and electronics)|FIFO]] order<ref name="summerfield">{{Cite book |last=Summerfield |first=Mark |title=Programming in Go: Creating Applications for the 21st Century |publisher=Addison-Wesley |year=2012}}</ref>{{rp|43}} and allow sending goroutines to proceed before their messages are received.<ref name=":0" />{{Rp|page=233}}

Channels are typed, so that a channel of type {{mono|chan ''T''}} can only be used to transfer messages of type {{mono|''T''}}. Special syntax is used to operate on them; {{mono|<-ch}} is an expression that causes the executing goroutine to block until a value comes in over the channel {{mono|ch}}, while {{mono|ch <- x}} sends the value {{mono|x}} (possibly blocking until another goroutine receives the value). The built-in {{mono|switch}}-like {{mono|select}} statement can be used to implement non-blocking communication on multiple channels; see [[#Concurrencyexample|below]] for an example. Go has a memory model describing how goroutines must use channels or other operations to safely share data.<ref>{{Cite web |url=http://golang.org/ref/mem |title=The Go Memory Model |access-date=April 10, 2017}}</ref>

The existence of channels does not by itself set Go apart from [[actor model]]-style concurrent languages like Erlang, where messages are addressed directly to actors (corresponding to goroutines). In the actor model, channels are themselves actors, therefore addressing a channel just means to address an actor. The actor style can be simulated in Go by maintaining a one-to-one correspondence between goroutines and channels, but the language allows multiple goroutines to share a channel or a single goroutine to send and receive on multiple channels.{{r|phrasebook}}{{rp|147}}

From these tools one can build concurrent constructs like worker pools, pipelines (in which, say, a file is decompressed and parsed as it downloads), background calls with timeout, "fan-out" parallel calls to a set of services, and others.<ref>{{Cite web |url=http://talks.golang.org/2012/concurrency.slide |title=Go Concurrency Patterns |website=The Go Programming Language}}</ref> Channels have also found uses further from the usual notion of interprocess communication, like serving as a concurrency-safe list of recycled buffers,<ref>{{cite web|last=Graham-Cumming|first=John|url=http://blog.cloudflare.com/recycling-memory-buffers-in-go|title=Recycling Memory Buffers in Go|date=August 24, 2013}}</ref> implementing [[coroutine]]s (which helped inspire the name ''goroutine''),<ref>{{Cite web|url=http://golang.org/doc/play/tree.go|title=tree.go}}</ref> and implementing [[iterator]]s.<ref>{{cite web|last=Cheslack-Postava |first=Ewen |url=http://ewencp.org/blog/golang-iterators/ |title=Iterators in Go}}</ref>

Concurrency-related structural conventions of Go ([[channel (programming)|channel]]s and alternative channel inputs) are derived from [[C. A. R. Hoare|Tony Hoare's]] [[communicating sequential processes]] model. Unlike previous concurrent programming languages such as [[Occam (programming language)|Occam]] or [[Limbo (programming language)|Limbo]] (a language on which Go co-designer Rob Pike worked),<ref>{{cite web|last=Kernighan|first=Brian W.|url=http://www.vitanuova.com/inferno/papers/descent.html|title=A Descent Into Limbo}}</ref> Go does not provide any built-in notion of safe or verifiable concurrency.<ref name="memmodel">{{cite web |url=http://golang.org/doc/go_mem.html |title=The Go Memory Model |access-date=January 5, 2011}}</ref> While the communicating-processes model is favored in Go, it is not the only one: all goroutines in a program share a single address space. This means that mutable objects and pointers can be shared between goroutines; see {{slink||Lack of data race safety}}, below.

====Suitability for parallel programming====
Although Go's concurrency features are not aimed primarily at [[parallel computing|parallel processing]],{{r|concurrency-is-not}} they can be used to program [[shared memory architecture|shared-memory]] [[multiprocessing|multi-processor]] machines. Various studies have been done into the effectiveness of this approach.<ref>{{cite conference |last=Tang |first=Peiyi |title=Multi-core parallel programming in Go |conference=Proc. First International Conference on Advanced Computing and Communications |year=2010 |url=http://www.ualr.edu/pxtang/papers/acc10.pdf |access-date=May 14, 2015 |archive-date=September 9, 2016 |archive-url=https://web.archive.org/web/20160909032631/http://www.ualr.edu/pxtang/papers/acc10.pdf |url-status=dead }}</ref> One of these studies compared the size (in [[lines of code]]) and speed of programs written by a seasoned programmer not familiar with the language and corrections to these programs by a Go expert (from Google's development team), doing the same for [[Chapel (programming language)|Chapel]], [[Cilk]] and [[Intel Threading Building Blocks|Intel TBB]]. The study found that the non-expert tended to write [[fork–join model|divide-and-conquer]] algorithms with one {{mono|go}} statement per recursion, while the expert wrote distribute-work-synchronize programs using one goroutine per processor core. The expert's programs were usually faster, but also longer.<ref>{{cite conference |last1=Nanz |first1=Sebastian |first2=Scott |last2=West |first3=Kaue |last3=Soares Da Silveira |title=Examining the expert gap in parallel programming |conference=Euro-Par 2013 |url=http://se.inf.ethz.ch/people/west/expert-gap-europar-2013.pdf |citeseerx=10.1.1.368.6137}}</ref>

====Lack of data race safety====
Go's approach to concurrency can be summarized as "don't communicate by sharing memory; share memory by communicating".<ref>{{cite web|title=Share Memory By Communicating|last=Go Authors|url=https://go.dev/doc/codewalk/sharemem/}}</ref> There are no restrictions on how goroutines access shared data, making [[Data race|data races]] possible. Specifically, unless a program explicitly synchronizes via channels or other means, writes from one goroutine might be partly, entirely, or not at all visible to another, often with no guarantees about ordering of writes.<ref name="memmodel" /> Furthermore, Go's ''internal data structures'' like interface values, slice headers, hash tables, and string headers are not immune to data races, so type and memory safety can be violated in multithreaded programs that modify shared instances of those types without synchronization.<ref>{{cite web|last=Cox|first=Russ|author-link=Russ Cox|url=http://research.swtch.com/gorace|title=Off to the Races}}</ref><ref name="SPLASH2012">{{cite web |last=Pike |first=Rob |author-link=Rob Pike |date=October 25, 2012 |title=Go at Google: Language Design in the Service of Software Engineering |url=http://talks.golang.org/2012/splash.article |publisher=Google, Inc.}} "There is one important caveat: Go is not purely memory safe in the presence of concurrency."</ref> Instead of language support, safe concurrent programming thus relies on conventions; for example, Chisnall recommends an idiom called "aliases [[exclusive or|xor]] mutable", meaning that passing a mutable value (or pointer) over a channel signals a transfer of ownership over the value to its receiver.{{r|phrasebook}}{{rp|155}} The gc toolchain has an optional data race detector that can check for unsynchronized access to shared memory during runtime since version 1.1,<ref>{{cite web |title=Introducing the Go Race Detector |url=https://go.dev/blog/race-detector |access-date=26 June 2013 |website=The Go Blog}}</ref> additionally a best-effort race detector is also included by default since version 1.6 of the gc runtime for access to the <code>map</code> data type.<ref>{{Cite web |title=Go 1.6 Release Notes - The Go Programming Language |url=https://go.dev/doc/go1.6 |access-date=2023-11-17 |website=go.dev |language=en}}</ref>

===Binaries===
The linker in the gc toolchain creates statically linked binaries by default; therefore all Go binaries include the Go runtime.<ref>{{Cite web | url=https://golang.org/doc/faq |title = Frequently Asked Questions (FAQ) - the Go Programming Language}}</ref><ref>{{Cite web | url=https://medium.com/@jondot/a-story-of-a-fat-go-binary-20edc6549b97 | title=A Story of a Fat Go Binary| date=September 21, 2018}}</ref>

===Omissions===
Go deliberately omits certain features common in other languages, including [[inheritance (object-oriented programming)|(implementation)&nbsp;inheritance]], [[Assertion (software development)|assertions]],{{efn|Language FAQ "Why does Go not have assertions? ...our experience has been that programmers use them as a crutch to avoid thinking about proper error handling and reporting...."<ref name="langfaq" />}} [[pointer arithmetic]],{{efn|name=noPointerArith|Language FAQ "Why is there no pointer arithmetic? Safety ... never derive an illegal address that succeeds incorrectly ... using array indices can be as efficient as ... pointer arithmetic ... simplify the implementation of the garbage collector...."<ref name="langfaq" />}} [[type conversion#Implicit type conversion|implicit type conversion]]s, [[union type#Untagged unions|untagged union]]s,{{efn|Language FAQ "Why are there no untagged unions...? [they] would violate Go's memory safety guarantees."<ref name="langfaq" />}} and [[tagged union]]s.{{efn|Language FAQ "Why does Go not have variant types? ... We considered [them but] they overlap in confusing ways with interfaces.... [S]ome of what variant types address is already covered, ... although not as elegantly."<ref name="langfaq" /> (The tag of an interface type<ref>{{cite web |url=https://golang.org/ref/spec#Interface_types |title=Go Programming Language Specification, §Interface types|work=The Go Programming Language}}</ref> is accessed with a type assertion<ref>{{cite web |url=https://golang.org/ref/spec#Type_assertion |title=Go Programming Language Specification, §Type assertions|work=The Go Programming Language}}</ref>).}} The designers added only those facilities that all three agreed on.<ref>{{cite interview |url=http://www.informit.com/articles/article.aspx?p=1623555 |website=informIT |title=All Systems Are Go |date=August 17, 2010 |access-date=June 21, 2018}}</ref>

Of the omitted language features, the designers explicitly argue against assertions and pointer arithmetic, while defending the choice to omit type inheritance as giving a more useful language, encouraging instead the use of [[protocol (object-oriented programming)|interfaces]] to achieve [[dynamic dispatch]]{{efn|Questions "How do I get dynamic dispatch of methods?" and "Why is there no type inheritance?" in the language FAQ.<ref name="langfaq" />}} and [[composition over inheritance|composition]] to reuse code. Composition and [[delegation (programming)|delegation]] are in fact largely automated by {{mono|struct}} embedding; according to researchers Schmager ''et al.'', this feature "has many of the drawbacks of inheritance: it affects the public interface of objects, it is not fine-grained (i.e, no method-level control over embedding), methods of embedded objects cannot be hidden, and it is static", making it "not obvious" whether programmers will overuse it to the extent that programmers in other languages are reputed to overuse inheritance.<ref name="gohotdraw">{{cite conference |last1=Schmager |first1=Frank |first2=Nicholas |last2=Cameron |first3=James |last3=Noble |title=GoHotDraw: evaluating the Go programming language with design patterns |conference=Evaluation and Usability of Programming Languages and Tools |publisher=ACM |year=2010}}</ref>

[[Exception handling]] was initially omitted in Go due to lack of a "design that gives value proportionate to the complexity".<ref>{{cite web |title=Language Design FAQ |url=http://golang.org/doc/go_lang_faq.html#absent_features |website= |date=13 November 2009 |archive-url=https://web.archive.org/web/20091113154906/http://golang.org/doc/go_lang_faq.html#absent_features |archive-date=13 November 2009 |url-status=dead}}</ref> An exception-like {{mono|panic}}/{{mono|recover}} mechanism that avoids the usual <code>try-catch</code> control structure was proposed<ref>{{cite web |url=https://groups.google.com/group/golang-nuts/browse_thread/thread/1ce5cd050bb973e4 |title=Proposal for an exception-like mechanism |date=March 25, 2010 |work=golang-nuts |access-date=March 25, 2010}}</ref> and released in the March 30, 2010 snapshot.<ref>{{cite web |url=http://golang.org/doc/devel/weekly.html#2010-03-30 |title=Weekly Snapshot History|work=The Go Programming Language}}</ref> The Go authors advise using it for unrecoverable errors such as those that should halt an entire program or server request, or as a shortcut to propagate errors up the stack within a package.<ref>{{cite web|url=https://code.google.com/p/go-wiki/wiki/PanicAndRecover|title=Panic And Recover|publisher=Go wiki}}</ref><ref>{{cite web |url=https://golang.org/doc/effective_go.html#panic |title=Effective Go |work=The Go Programming Language}}</ref> Across package boundaries, Go includes a canonical error type, and multi-value returns using this type are the standard idiom.<ref name="langfaq" />

==Style==
The Go authors put substantial effort into influencing the style of Go programs:

* Indentation, spacing, and other surface-level details of code are automatically standardized by the <code>gofmt</code> tool. It uses tabs for indentation and blanks for alignment. Alignment assumes that an editor is using a fixed-width font.<ref>{{Cite web|title=gofmt |url=https://golang.org/cmd/gofmt/|access-date=2021-02-05|website=The Go Programming Language}}</ref> <code>golint</code> does additional style checks automatically, but has been deprecated and archived by the Go maintainers.<ref>{{Cite web|title=golang/lint public archive|url=https://github.com/golang/lint|website=github.com|date=November 30, 2022 }}</ref>
* Tools and libraries distributed with Go suggest standard approaches to things like API documentation (<code>godoc</code>),<ref name="eff">{{cite web |url=http://golang.org/doc/effective_go.html |title=Effective Go |work=The Go Programming Language}}</ref> testing (<code>go test</code>), building (<code>go build</code>), package management (<code>go get</code>), and so on.
* Go enforces rules that are recommendations in other languages, for example banning cyclic dependencies, unused variables<ref>{{Cite web|title=Unused local variables|url=https://yourbasic.org/golang/unused-local-variables/|access-date=2021-02-11|website=yourbasic.org|language=en}}</ref> or imports,<ref>{{Cite web|title=Unused package imports|url=https://yourbasic.org/golang/unused-imports/|access-date=2021-02-11|website=yourbasic.org|language=en}}</ref> and implicit type conversions.
* The ''omission'' of certain features (for example, functional-programming shortcuts like <code>map</code> and Java-style <code>try</code>/<code>finally</code> blocks) tends to encourage a particular explicit, concrete, and imperative programming style.
* On day one the Go team published a collection of Go idioms,<ref name="eff" /> and later also collected code review comments,<ref>{{cite web |title=Code Review Comments |website=[[GitHub]] |url=https://github.com/golang/go/wiki/CodeReviewComments |access-date=July 3, 2018}}</ref> talks,<ref>{{cite web |title=Talks |url=https://talks.golang.org/ |access-date=July 3, 2018}}</ref> and official blog posts<ref>{{cite web |title=Errors Are Values |url=http://blog.golang.org/errors-are-values |access-date=July 3, 2018}}</ref> to teach Go style and coding philosophy.

==Tools==
The main Go distribution includes tools for [[build automation|building]], [[unit testing|testing]], and [[static program analysis|analyzing]] code:

* <code>go build</code>, which builds Go binaries using only information in the source files themselves, no separate makefiles
* <code>go test</code>, for unit testing and microbenchmarks as well as fuzzing
* <code>go fmt</code>, for formatting code
* <code>go install</code>, for retrieving and installing remote packages
* <code>go vet</code>, a static analyzer looking for potential errors in code
* <code>go run</code>, a shortcut for building and executing code
* <code>godoc</code>, for displaying documentation or serving it via HTTP
* <code>gorename</code>, for renaming variables, functions, and so on in a type-safe way
* <code>go generate</code>, a standard way to invoke code generators
* <code>go mod</code>, for creating a new module, adding dependencies, upgrading dependencies, etc.

It also includes [[profiling (computer programming)|profiling]] and [[debugging]] support, [[fuzzing]] capabilities to detect bugs, [[Run time (program lifecycle phase)|runtime]] instrumentation (for example, to track [[Garbage collection (computer science)|garbage collection]] pauses), and a [[data race]] detector.

Another tool maintained by the Go team but is not included in Go distributions is <code>gopls</code>, a language server that provides [[Integrated development environment|IDE]] features such as [[intelligent code completion]] to [[Language Server Protocol]] compatible editors.<ref>{{Cite web |title=tools/gopls/README.md at master · golang/tools |url=https://github.com/golang/tools/blob/master/gopls/README.md |access-date=2023-11-17 |website=GitHub |language=en}}</ref>

An ecosystem of third-party tools adds to the standard distribution, such as <code>gocode</code>, which enables code autocompletion in many text editors, <code>goimports</code>, which automatically adds/removes package imports as needed, and <code>errcheck</code>, which detects code that might unintentionally ignore errors.

==Examples==
===Hello world===
<syntaxhighlight lang="go">
<syntaxhighlight lang="go">
package main
package main
Line 103: Line 290:


func main() {
func main() {
fmt.Println("Hello, World")
fmt.Println("hello world")
}
}
</syntaxhighlight>
</syntaxhighlight>


where "fmt" is the package for ''formatted [[Input/output|I/O]]'', similar to C's [[C file input/output]].<ref>{{Cite web|url=https://golang.org/pkg/fmt/|title=fmt |website=The Go Programming Language|access-date=2019-04-08}}</ref>
Go's automatic [[semicolon]] insertion feature requires that opening braces not be placed on their own lines, and this is thus the preferred [[brace style]]; the examples shown comply with this style.<ref>{{cite web|url=http://golang.org/doc/go_tutorial.html|title=A Tutorial for the Go Programming Language|work=The Go Programming Language|publisher=Google|accessdate=10 March 2010|quote=The one surprise is that it's important to put the opening brace of a construct such as an if statement on the same line as the if; however, if you don't, there are situations that may not compile or may give the wrong result. The language forces the brace style to some extent.}}</ref>


==={{anchor|Concurrencyexample}}Concurrency===
===Echo===
The following simple program demonstrates Go's [[#Concurrency|concurrency feature]]s to implement an asynchronous program. It launches two lightweight threads ("goroutines"): one waits for the user to type some text, while the other implements a timeout. The {{mono|select}} statement waits for either of these goroutines to send a message to the main routine, and acts on the first message to arrive (example adapted from David Chisnall's book).<ref name="phrasebook">{{cite book |title=The Go Programming Language Phrasebook |first=David |last=Chisnall |publisher=Addison-Wesley |year=2012 |isbn=9780132919005 |url=https://books.google.com/books?id=scyH562VXZUC}}</ref>{{rp|152}}

Example illustrating how to write a program like the Unix [[Echo (command)|echo command]] in Go:<ref>{{cite web|url=http://golang.org/doc/go_tutorial.html|title=A Tutorial for the Go Programming Language|date=16 January 2010|work=golang.org|accessdate=18 January 2010}}</ref>


<syntaxhighlight lang="go">
<syntaxhighlight lang="go">
Line 117: Line 303:


import (
import (
"os"
"fmt"
"time"
"flag" // Command line option parser.
)
)


func readword(ch chan string) {
var omitNewline = flag.Bool("n", false, "don't print final newline")
fmt.Println("Type a word, then hit Enter.")
var word string
fmt.Scanf("%s", &word)
ch <- word
}


func timeout(t chan bool) {
const (
time.Sleep(5 * time.Second)
Space = " "
Newline = "\n"
t <- false
}
)


func main() {
func main() {
t := make(chan bool)
flag.Parse() // Scans the arg list and sets up flags.
var s string
go timeout(t)

for i := 0; i < flag.NArg(); i++ {
if i > 0 {
ch := make(chan string)
s += Space
go readword(ch)

}
select {
s += flag.Arg(i)
case word := <-ch:
fmt.Println("Received", word)
case <-t:
fmt.Println("Timeout.")
}
}
if !*omitNewline {
s += Newline
}
os.Stdout.WriteString(s)
}
}
</syntaxhighlight>
</syntaxhighlight>


==Reception==
===Testing===
The testing package provides support for automated testing of go packages.<ref>{{Cite web|title=testing |url=https://golang.org/pkg/testing/|access-date=2020-12-27|website=The Go Programming Language}}</ref> Target function example:


<syntaxhighlight lang="go">
Go's initial release led to much discussion.
func ExtractUsername(email string) string {
at := strings.Index(email, "@")
return email[:at]
}
</syntaxhighlight>


Test code (note that '''assert''' keyword is missing in Go; tests live in <filename>_test.go at the same package):
Michele Simionato wrote in an article for artima.com:<ref>{{cite news |url=http://www.artima.com/weblogs/viewpost.jsp?thread=274019 |title=Interfaces vs Inheritance (or, watch out for Go!) |last= Simionato |first=Michele |date=15 November 2009 |publisher=artima |accessdate=15 November 2009}}</ref>


<syntaxhighlight lang="go">
{{quote |Here I just wanted to point out the design choices about interfaces and inheritance. Such ideas are not new and it is a shame that no popular language has followed such particular route in the design space. I hope Go will become popular; if not, I hope such ideas will finally enter in a popular language, we are already 10 or 20 years too late :-(}}
import (
"testing"
)


func TestExtractUsername(t *testing.T) {
[[Dave Astels]] at [[Engine Yard]] wrote:<ref>{{cite news |url=http://www.engineyard.com/blog/2009/ready-set-go/ |title=Ready, Set, Go! |last= Astels |first=Dave |date=9 November 2009 |publisher=engineyard |accessdate=9 November 2009}}</ref>
t.Run("withoutDot", func(t *testing.T) {
username := ExtractUsername("r@google.com")
if username != "r" {
t.Fatalf("Got: %v\n", username)
}
})


t.Run("withDot", func(t *testing.T) {
{{quote |Go is extremely easy to dive into. There are a minimal number of fundamental language concepts and the [[Syntax (programming languages)|syntax]] is clean and designed to be clear and unambiguous. Go is still experimental and still a little rough around the edges.}}
username := ExtractUsername("jonh.smith@example.com")
if username != "jonh.smith" {
t.Fatalf("Got: %v\n", username)
}
})
}
</syntaxhighlight>


It is possible to run tests in parallel.
''[[Ars Technica]]'' interviewed Rob Pike, one of the authors of Go, and asked why a new language was needed. He replied that:<ref name="ars">{{cite news |url=http://arstechnica.com/open-source/news/2009/11/go-new-open-source-programming-language-from-google.ars |title=Go: new open source programming language from Google |last=Paul |first=Ryan |date=10 November 2009 |publisher=Ars Technica |accessdate=13 November 2009}}</ref>


===Web app===
{{quote |It wasn't enough to just add features to existing programming languages, because sometimes you can get more in the long run by taking things away. They wanted to start from scratch and rethink everything. ... [But they did not want] to deviate too much from what developers already knew because they wanted to avoid alienating Go's target audience.}}
The [https://pkg.go.dev/net/http net/http]<ref>{{Cite web |title=http package - net/http - Go Packages |url=https://pkg.go.dev/net/http |access-date=2024-11-23 |website=pkg.go.dev}}</ref> package provides support for creating web applications.


This example would show "Hello world!" when localhost:8080 is visited.
Go was named Programming Language of the Year by the [[TIOBE Programming Community Index]] in its first year, 2009, for having a larger 12-month increase in popularity (in only 2 months, after its introduction in November) than any other language that year, and reached 13th place by January of 2010<ref>{{cite web|first=jt|title=Google's Go Wins Programming Language Of The Year Award|url=http://jaxenter.com/google-s-go-wins-programming-language-of-the-year-award-10069.html|publisher=jaxenter|accessdate=5 December 2012}}</ref>, surpassing established languages like [[Pascal (programming language)|Pascal]]. {{As of|2012|3|}}, it ranked 66th in the index.<ref>{{cite web |url=http://es.scribd.com/doc/89569304/TIOBE-Programming-Community-Index-for-March-2012 |title=TIOBE Programming Community Index for March 2012 |date=March 2012 |publisher=TIOBE Software |accessdate=28 April 2012}}</ref>
<syntaxhighlight lang="go">
package main


import (
[[Bruce Eckel]] stated:<ref>{{cite web |url=http://www.artima.com/weblogs/viewpost.jsp?thread=333589 |title=Calling Go from Python via JSON-RPC |date=27 |month=August |year=2011 |author=Bruce Eckel |accessdate=29 August 2011}}</ref>
"fmt"
{{quote |The complexity of [[C++]] (even more complexity has been added in the new C++), and the resulting impact on productivity, is no longer justified. All the hoops that the C++ programmer had to jump through in order to use a C-compatible language make no sense anymore -- they're just a waste of time and effort. Now, Go makes much more sense for the class of problems that C++ was originally intended to solve.}}
"log"
"net/http"
)

func helloFunc(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello world!")
}

func main() {
http.HandleFunc("/", helloFunc)
log.Fatal(http.ListenAndServe(":8080", nil))
}

</syntaxhighlight>

== Applications ==
Go has found widespread adoption in various domains due to its robust standard library and ease of use.<ref name="code-mag-2022-11-24">{{cite magazine|last=Lee|first=Wei-Meng|url=https://www.codemag.com/Article/2011051/Introduction-to-the-Go-Programming-Language|magazine=[[Component Developer Magazine]]|archive-url=https://web.archive.org/web/20230605071554/https://www.codemag.com/Article/2011051/Introduction-to-the-Go-Programming-Language|date=24 November 2022|title=Introduction to the Go Programming Language|archive-date=5 June 2023|access-date=8 September 2023}}</ref>

Popular applications include: [[Caddy (web server)|Caddy]], a web server that automates the process of setting up HTTPS,<ref name="linuxmag-213-2018">{{cite magazine |last1=Hoffmann |first1=Frank |last2=Neumeyer |first2=Mandy |url=https://www.linux-magazine.com/Issues/2018/213/Caddy |title=Simply Secure |magazine=[[Linux Magazine]] |date=August 2018 |issue=213 |archive-url=https://web.archive.org/web/20230528175545/https://www.linux-magazine.com/Issues/2018/213/Caddy |archive-date=2023-05-28 |access-date=8 September 2023}}</ref> [[Docker (software)|Docker]], which provides a platform for containerization, aiming to ease the complexities of software development and deployment,<ref name="codemag-20220831">{{cite magazine |last=Lee |first=Wei-Meng |url=https://www.codemag.com/Article/2103061/Introduction-to-Containerization-Using-Docker |title=Introduction to Containerization Using Docker |magazine=[[Component Developer Magazine|CODE Magazine]] |date=31 August 2022 |archive-url=https://web.archive.org/web/20230530073551/https://www.codemag.com/Article/2103061/Introduction-to-Containerization-Using-Docker |archive-date=30 May 2023 |url-status=live |access-date=8 September 2023}}</ref> [[Kubernetes]], which automates the deployment, scaling, and management of containerized applications,<ref name="codemag-20230224">{{cite magazine |last=Pirker |first=Alexander |url=https://www.codemag.com/Article/2303071/Kubernetes-Security-for-Starters |title=Kubernetes Security for Starters |magazine=[[Component Developer Magazine|CODE Magazine]] |date=24 February 2023 |archive-url=https://web.archive.org/web/20230401212416/https://codemag.com/Article/2303071/Kubernetes-Security-for-Starters |archive-date=1 April 2023 |url-status=live |access-date=8 September 2023}}</ref> [[CockroachDB]], a distributed SQL database engineered for scalability and strong consistency,<ref name="sigmod20-cockroach">{{cite conference |last1=Taft |first1=Rebecca |last2=Sharif |first2=Irfan |last3=Matei |first3=Andrei |last4=Van Benschoten |first4=Nathan |last5=Lewis |first5=Jordan |last6=Grieger |first6=Tobias |last7=Niemi |first7=Kai |last8=Woods |first8= Andy |last9=Birzin |first9=Anne |last10=Poss |first10=Raphael |last11=Bardea |first11=Paul |last12=Ranade |first12=Amruta |last13=Darnell |first13=Ben |last14=Gruneir |first14=Bram |last15=Jaffray |first15=Justin |last16=Zhang |first16=Lucy |last17=Mattis |first17=Peter |doi=10.1145/3318464.3386134 |title=Proceedings of the 2020 ACM SIGMOD International Conference on Management of Data |isbn=978-1-4503-6735-6 |article=CockroachDB: The Resilient Geo-Distributed SQL Database |conference=[[SIGMOD]] '20 |date=11 June 2020 |pages=1493–1509 |doi-access=free }}</ref> and [[Hugo (software)|Hugo]], a static site generator that prioritizes speed and flexibility, allowing developers to create websites efficiently.<ref name="linuxjournal-20220913">{{cite news |last=Hopkins |first=Brandon |url=https://www.linuxjournal.com/content/static-site-generation-hugo |title=Static Site Generation with Hugo |work=Linux Journal |date=13 September 2022 |archive-url=https://web.archive.org/web/20230408065506/https://www.linuxjournal.com/content/static-site-generation-hugo |archive-date=8 April 2023 |url-status=live |access-date=8 September 2023}}</ref>

==Reception==
The interface system, and the deliberate omission of inheritance, were praised by Michele Simionato, who likened these characteristics to those of [[Standard ML]], calling it "a shame that no popular language has followed [this] particular route".<ref>{{cite news |url=http://www.artima.com/weblogs/viewpost.jsp?thread=274019 |title=Interfaces vs Inheritance (or, watch out for Go!) |last= Simionato |first=Michele |date=November 15, 2009 |publisher=artima |access-date=November 15, 2009}}</ref>

Dave Astels at [[Engine Yard]] wrote in 2009:<ref>{{cite news|url=https://www.engineyard.com/blog/ready-set-go|title=Ready, Set, Go!|last=Astels|first=Dave|date=November 9, 2009|access-date=November 9, 2009|publisher=engineyard|archive-date=October 19, 2018|archive-url=https://web.archive.org/web/20181019164102/https://www.engineyard.com/blog/ready-set-go|url-status=dead}}</ref>
{{blockquote |Go is extremely easy to dive into. There are a minimal number of fundamental language concepts and the [[syntax (programming languages)|syntax]] is clean and designed to be clear and unambiguous.

Go ''is'' still experimental and still a little rough around the edges.|sign=|source=}}

Go was named Programming Language of the Year by the [[TIOBE Programming Community Index]] in its first year, 2009, for having a larger 12-month increase in popularity (in only 2 months, after its introduction in November) than any other language that year, and reached 13th place by January 2010,<ref>{{cite web |author=jt |title=Google's Go Wins Programming Language Of The Year Award |date=January 11, 2010 |url=http://jaxenter.com/google-s-go-wins-programming-language-of-the-year-award-10069.html |publisher=jaxenter |access-date=December 5, 2012}}</ref> surpassing established languages like [[Pascal (programming language)|Pascal]]. By June 2015, its ranking had dropped to below 50th in the index, placing it lower than [[COBOL]] and [[Fortran]].<ref>{{cite web |url=http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html |title=TIOBE Programming Community Index for June 2015 |date=June 2015 |publisher=TIOBE Software |access-date=July 5, 2015}}</ref> But as of January 2017, its ranking had surged to 13th, indicating significant growth in popularity and adoption. Go was again awarded TIOBE Programming Language of the Year in 2016.<ref>{{Cite web |title=TIOBE Index |url=https://www.tiobe.com/tiobe-index/ |access-date=2024-07-15 |website=TIOBE |language=en-US}}</ref>

[[Bruce Eckel]] has stated:<ref>{{cite web |url=http://www.artima.com/weblogs/viewpost.jsp?thread=333589 |title=Calling Go from Python via JSON-RPC |date=August 27, 2011 |last=Eckel |first=Bruce |access-date=August 29, 2011}}</ref>
{{blockquote|The complexity of [[C++]] (even more complexity has been added in the new C++), and the resulting impact on productivity, is no longer justified. All the hoops that the C++ programmer had to jump through in order to use a C-compatible language make no sense anymore -- they're just a waste of time and effort. Go makes much more sense for the class of problems that C++ was originally intended to solve.}}

A 2011 evaluation of the language and its {{mono|gc}} implementation in comparison to C++ ([[GNU Compiler Collection|GCC]]), Java and [[Scala (programming language)|Scala]] by a Google engineer found:

{{blockquote|Go offers interesting language features, which also allow for a concise and standardized notation. The compilers for this language are still immature, which reflects in both performance and binary sizes.|R. Hundt<ref>{{cite conference |last=Hundt |first=Robert |title=Loop recognition in C++/Java/Go/Scala |conference=Scala Days |year=2011 |url=https://days2011.scala-lang.org/sites/days2011/files/ws3-1-Hundt.pdf}}</ref>}}

The evaluation got a rebuttal from the Go development team. Ian Lance Taylor, who had improved the Go code for Hundt's paper, had not been aware of the intention to publish his code, and says that his version was "never intended to be an example of idiomatic or efficient Go"; Russ Cox then optimized the Go code, as well as the C++ code, and got the Go code to run almost as fast as the C++ version and more than an order of magnitude faster than the code in the paper.<ref>{{cite web |title=Google Go strikes back with C++ bake-off |first=Cade |last=Metz |date=July 1, 2011 |website=[[The Register]] |url=https://www.theregister.co.uk/2011/07/01/go_v_cpluplus_redux/}}</ref>

* Go's ''[[null pointer|nil]]'' combined with the lack of [[algebraic types]] leads to difficulty handling failures and [[Base case (recursion)|base case]]s.<ref name="yager">{{cite web | first = Will | last = Yager | url = http://yager.io/programming/go.html | title = Why Go is not Good | access-date = 4 November 2018}}</ref><ref name="dobronszki">{{cite web | first = Janos | last = Dobronszki | url = https://crufter.com/everyday-hassles-in-go | title = Everyday Hassles in Go | access-date = 4 November 2018}}</ref>
* Go does not allow an opening brace to appear on its own line, which forces all Go programmers to use the same brace style.<ref>{{cite web|title=Why are there braces but no semicolons? And why can't I put the opening brace on the next line?|quote=The advantages of a single, programmatically mandated format for all Go programs greatly outweigh any perceived disadvantages of the particular style.|url=https://golang.org/doc/faq#semicolons|access-date=March 26, 2020}}</ref>
* Go has been criticized for focusing on simplicity of implementation rather than correctness and flexibility; as an example, the language uses [[POSIX]] file semantics on all platforms, and therefore provides incorrect information on platforms such as [[Microsoft Windows|Windows]] (which do not follow the aforementioned standard).<ref>{{cite web|title=I want off Mr. Golang's Wild Ride|url=https://fasterthanli.me/articles/i-want-off-mr-golangs-wild-ride|date=February 28, 2020|access-date=November 17, 2020}}</ref><ref>{{cite web|title=proposal: os: Create/Open/OpenFile() set FILE_SHARE_DELETE on windows #32088|website=[[GitHub]]|url=https://github.com/golang/go/issues/32088|date=May 16, 2019|access-date=November 17, 2020}}</ref>
* A study showed that it is as easy to make concurrency bugs with message passing as with shared memory, sometimes even more.<ref>{{Cite web|last=Tu|first=Tengfei|date=2019|title=Understanding Real-World Concurrency Bugs in Go|url=https://songlh.github.io/paper/go-study.pdf|quote=For example, around 58% of blocking bugs are caused by message passing. In addition to the violation of Go's channel usage rules (e.g., waiting on a channel that no one sends data to or close), many concurrency bugs are caused by the mixed usage of message passing and other new semantics and new libraries in Go, which can easily be overlooked but hard to detect}}</ref>


==Naming dispute==
==Naming dispute==
On the day of the general release of the language, Francis McCabe, developer of the [[Go! (programming language)|Go! programming language]] (note the [[exclamation point]]), requested a name change of Google's language to prevent confusion with his language.<ref name="infoweek">{{cite news|url=http://www.informationweek.com/news/software/web_services/showArticle.jhtml?articleID=221601351|title=Google 'Go' Name Brings Accusations Of Evil'|last=Claburn|first=Thomas|date=11 November 2009|publisher=InformationWeek|accessdate=18 January 2010}}</ref> The issue was closed by a Google developer on 12 October 2010 with the custom status "Unfortunate", with a comment that "there are many computing products and services named Go. In the 11 months since our release, there has been minimal confusion of the two languages."<ref>{{cite web|url=http://code.google.com/p/go/issues/detail?id=9|title=Issue 9 - go - I have already used the name for *MY* programming language|work=Google Code|publisher=[[Google Inc.]]|accessdate=12 October 2010}}</ref>
On November 10, 2009, the day of the general release of the language, Francis McCabe, developer of the [[Go! (programming language)|Go! programming language]] (note the exclamation point), requested a name change of Google's language to prevent confusion with his language, which he had spent 10 years developing.<ref>{{cite news |url=http://www.geek.com/news/google-didnt-google-go-before-naming-their-programming-language-977351/ |title=Google didn't google "Go" before naming their programming language' |last=Brownlee |first=John |date=November 13, 2009 |access-date=May 26, 2016 |archive-date=December 8, 2015 |archive-url=https://web.archive.org/web/20151208143907/http://www.geek.com/news/google-didnt-google-go-before-naming-their-programming-language-977351/ |url-status=dead }}</ref> McCabe raised concerns that "the 'big guy' will end up steam-rollering over" him, and this concern resonated with the more than 120 developers who commented on Google's official issues thread saying they should change the name, with some<ref name="infoweek">{{cite news |url=http://www.informationweek.com/news/software/web_services/showArticle.jhtml?articleID=221601351 |title=Google 'Go' Name Brings Accusations Of Evil' |last=Claburn |first=Thomas |date=November 11, 2009 |publisher=InformationWeek |access-date=January 18, 2010 |archive-date=July 22, 2010 |archive-url=https://web.archive.org/web/20100722010320/http://www.informationweek.com/news/software/web_services/showArticle.jhtml?articleID=221601351 |url-status=dead }}</ref> even saying the issue contradicts Google's motto of: [[Don't be evil]].<ref name="issue9">{{cite web|url=https://github.com/golang/go/issues/9#issuecomment-66047478|title=Issue 9 - go&nbsp;— I have already used the name for *MY* programming language|work=Github|publisher=[[Google Inc.]]|access-date=October 12, 2010}}</ref>

On October 12, 2010, the filed public issue ticket was closed by Google developer Russ Cox (@rsc) with the custom status "Unfortunate" accompanied by the following comment: <blockquote>"There are many computing products and services named Go. In the 11 months since our release, there has been minimal confusion of the two languages."<ref name="issue9"/></blockquote>


==See also==
==See also==
{{Portal|Free and open-source software}}
* [[Fat pointer]]
* [[Comparison of programming languages]]
* [[Comparison of programming languages]]

==Notes==
{{Notelist}}


==References==
==References==
{{hatnote|This article incorporates material from the [http://golang.org/doc/go_tutorial.html official Go tutorial], which is licensed under the Creative Commons Attribution 3.0 license.}}
{{Hatnote|This article incorporates material from the [http://golang.org/doc/go_tutorial.html official Go tutorial], which is licensed under the Creative Commons Attribution 3.0 license.}}
{{Reflist|2}}
{{Reflist}}


==Further reading==
==Further reading==
{{Refbegin}}
*{{cite book|last=Chisnall|first=David|title=The Go Programming Language Phrasebook|url=http://www.informit.com/articles/article.aspx?p=1760496|date=9 May 2012|publisher=[[Addison-Wesley Professional]]|isbn=0-321-81714-1|chapter=Common Go Patterns}}
* {{Cite book
*{{cite book|last=Summerfield|first=Mark|title=Programming in Go: Creating Applications for the 21st Century|date=5 May 2012|publisher=[[Addison-Wesley Professional]]|isbn=0-321-77463-9|url=http://www.informit.com/store/product.aspx?isbn=0321774639}}
| first1 = Alan
| last1 = Donovan
| first2 = Brian
| last2 = Kernighan
| date = October 2015
| title = The Go Programming Language
| publisher = [[Addison-Wesley Professional]]
| edition = 1st
| pages = 400
| isbn = 978-0-13-419044-0
| url = https://www.informit.com/store/go-programming-language-9780134190440
}}
* {{Cite book
| first1 = Jon
| last1 = Bodner
| date = March 2021
| title = Learning Go
| publisher = [[O'Reilly Media|O'Reilly]]
| edition = 1st
| pages = 352
| isbn = 9781492077213
| url = https://www.oreilly.com/library/view/learning-go/9781492077206/
}}
{{Refend}}


==External links==
==External links==
{{Commons category|Go (programming language)}}
<!--========================({{No More Links}})============================
* {{Official website}}
| PLEASE BE CAUTIOUS IN ADDING MORE LINKS TO THIS ARTICLE. WIKIPEDIA |

| IS NOT A COLLECTION OF LINKS NOR SHOULD IT BE USED FOR ADVERTISING. |
{{Prone to spam|date=June 2013}}<!-- {{No more links}}
| |

| Excessive or inappropriate links WILL BE DELETED. |
Please be cautious adding more external links.
| See [[Wikipedia:External links]] & [[Wikipedia:Spam]] for details. |

| |
Wikipedia is not a collection of links and should not be used for advertising.
| If there are already plentiful links, please propose additions or |

| replacements on this article's discussion page, or submit your link |
Excessive or inappropriate links will be removed.
| to the relevant category at the Open Directory Project (dmoz.org) |

| and link back to that category using the {{dmoz}} template. |
See [[Wikipedia:External links]] and [[Wikipedia:Spam]] for details.
=======================({{No More Links}})=============================-->

* {{Official website|http://golang.org}}
If there are already suitable links, propose additions or replacements on
*{{cite web|url=http://www.stanford.edu/class/ee380/Abstracts/100428.html|title=Another Go at Language Design|last=Pike|first=Rob|date=28 April 2010|work=Stanford EE Computer Systems Colloquium|publisher=[[Stanford University]]}} ([http://ee380.stanford.edu/cgi-bin/videologger.php?target=100428-ee380-300.asx video]) — A university lecture
the article's talk page, or submit your link to the relevant category at
*{{Cite podcast |url= http://thechangelog.com/post/259401776/episode-0-0-3-googles-go-programming-language |title= Episode 0.0.3 - Google’s Go Programming Language |website= The Changelog | host= Wynn Netherland & Adam Stacoviak |date= 27 November 2009}} — Interview with Rob Pike, Tech Lead for the Google Go team
the Open Directory Project (dmoz.org) and link there using {{Dmoz}}.
* [http://go-lang.cat-v.org/ Go Programming Language Resources] (unofficial)
* irc://chat.freenode.net/#go-nuts – the [[IRC]] channel #go-nuts on [[freenode]]
* {{cite podcast|url=http://www.codingbynumbers.com/2011/01/coding-by-numbers-episode-20-interview.html |title=Episode 20 (Interview with Andrew Gerrand about Go Programming Language) |website=Coding By Numbers |publisher= |host=Steve Dalton |date=22 January 2011}}
*{{cite web|url=http://www.infoq.com/interviews/pike-google-go|title=Rob Pike on Google Go: Concurrency, Type System, Memory Management and GC|last=Schuster|first=Werner|date=25 February 2011|work=InfoQ|publisher=C4Media Inc.|location=GOTO Conference}}


-->
{{Google Inc.}}
{{Programming languages}}
{{Google FOSS}}
{{Rob Pike navbox}}
{{Rob Pike navbox}}
{{Ken Thompson navbox}}
{{Ken Thompson navbox}}


{{Authority control}}
{{Use dmy dates|date=August 2011}}


[[Category:Go (programming language)| ]]
{{DEFAULTSORT:Go (Programming Language)}}
[[Category:American inventions]]
[[Category:C programming language family]]
[[Category:C programming language family]]
[[Category:Concurrent programming languages]]
[[Category:Concurrent programming languages]]
[[Category:Cross-platform free software]]
[[Category:Cross-platform software]]
[[Category:Free and open source compilers]]
[[Category:Google software]]
[[Category:Google software]]
[[Category:High-level programming languages]]
[[Category:Procedural programming languages]]
[[Category:Procedural programming languages]]
[[Category:Programming languages]]
[[Category:Programming languages created in 2009]]
[[Category:Software using the BSD license]]
[[Category:Statically typed programming languages]]
[[Category:Systems programming languages]]
[[Category:Systems programming languages]]
[[Category:Cross-platform software]]
[[Category:Programming languages created in 2009]]
[[Category:American inventions]]

[[ar:غو (لغة برمجة)]]
[[bg:Go (език за програмиране)]]
[[cs:Go (programovací jazyk)]]
[[da:Go (programmeringssprog)]]
[[de:Go (Programmiersprache)]]
[[es:Go (lenguaje de programación)]]
[[fa:گو (زبان برنامه‌نویسی)]]
[[fr:Go (langage)]]
[[gu:ગો (પ્રોગ્રામિંગ ભાષા)]]
[[ko:Go (프로그래밍 언어)]]
[[it:Go (linguaggio di programmazione)]]
[[he:Go (שפת תכנות)]]
[[hu:Go (programozási nyelv)]]
[[ms:Go (bahasa pengaturcaraan)]]
[[nl:Go (programmeertaal)]]
[[ja:Go (プログラミング言語)]]
[[no:Go (programmeringsspråk)]]
[[pl:Go (język programowania)]]
[[pt:Go (linguagem de programação)]]
[[ru:Go]]
[[sr:Гоу]]
[[fi:Go (ohjelmointikieli)]]
[[sv:Go (programspråk)]]
[[ta:கோ (நிரலாக்க மொழி)]]
[[tr:Go (programlama dili)]]
[[uk:Go (мова програмування)]]
[[vi:Go (ngôn ngữ lập trình)]]
[[zh:Go]]

Latest revision as of 05:38, 9 December 2024

Go
ParadigmMulti-paradigm: concurrent imperative, functional[1] object-oriented[2][3]
Designed byRobert Griesemer
Rob Pike
Ken Thompson[4]
DeveloperThe Go Authors[5]
First appearedNovember 10, 2009; 15 years ago (2009-11-10)
Stable release
1.23.3 / 6 November 2024; 42 days ago (6 November 2024)
Typing disciplineInferred, static, strong,[6] structural,[7][8] nominal
Memory managementGarbage collection
Implementation languageGo, Assembly language (gc); C++ (gofrontend)
OSDragonFly BSD, FreeBSD, Linux, macOS, NetBSD, OpenBSD,[9] Plan 9,[10] Solaris, Windows
License3-clause BSD[5] + patent grant[11]
Filename extensions.go
Websitego.dev
Major implementations
gc, gofrontend
Influenced by
C, Oberon-2, Limbo, Active Oberon, communicating sequential processes, Pascal, Oberon, Smalltalk, Newsqueak, Modula-2, Alef, APL, BCPL, Modula, occam
Influenced
Crystal, V

Go is a fast[12] statically typed, compiled high-level general purpose programming language. It is known for its simplicity and efficiency.[13] Its simplicity express through its basic syntax of the language itself and its large library that help the developer to have a small stack for its project. It was designed at Google[14] in 2009 by Robert Griesemer, Rob Pike, and Ken Thompson.[4] It is syntactically similar to C, but also has memory safety, garbage collection, structural typing,[7] and CSP-style concurrency.[15] It is often referred to as Golang because of its former domain name, golang.org, but its proper name is Go.[16]

There are two major implementations:

  • The original, self-hosting[17] compiler toolchain, initially developed inside Google;[18]
  • A frontend written in C++, called gofrontend,[19] originally a GCC frontend, providing gccgo, a GCC-based Go compiler;[20] later extended to also support LLVM, providing an LLVM-based Go compiler called gollvm.[21]

A third-party source-to-source compiler, GopherJS,[22] compiles Go to JavaScript for front-end web development.

History

[edit]

Go was designed at Google in 2007 to improve programming productivity in an era of multicore, networked machines and large codebases.[23] The designers wanted to address criticisms of other languages in use at Google, but keep their useful characteristics:[24]

Its designers were primarily motivated by their shared dislike of C++.[26][27][28]

Go was publicly announced in November 2009,[29] and version 1.0 was released in March 2012.[30][31] Go is widely used in production at Google[32] and in many other organizations and open-source projects.

Branding and styling

[edit]
Mascot of Go programming language is a Gopher shown above.

The Gopher mascot was introduced in 2009 for the open source launch of the language. The design, by Renée French, borrowed from a c. 2000 WFMU promotion.[33]

In November 2016, the Go and Go Mono fonts were released by type designers Charles Bigelow and Kris Holmes specifically for use by the Go project. Go is a humanist sans-serif resembling Lucida Grande, and Go Mono is monospaced. Both fonts adhere to the WGL4 character set and were designed to be legible with a large x-height and distinct letterforms. Both Go and Go Mono adhere to the DIN 1450 standard by having a slashed zero, lowercase l with a tail, and an uppercase I with serifs.[34][35]

In April 2018, the original logo was redesigned by brand designer Adam Smith. The new logo is a modern, stylized GO slanting right with trailing streamlines. (The Gopher mascot remained the same.[36])

Generics

[edit]

The lack of support for generic programming in initial versions of Go drew considerable criticism.[37] The designers expressed an openness to generic programming and noted that built-in functions were in fact type-generic, but are treated as special cases; Pike called this a weakness that might be changed at some point.[38] The Google team built at least one compiler for an experimental Go dialect with generics, but did not release it.[39]

In August 2018, the Go principal contributors published draft designs for generic programming and error handling and asked users to submit feedback.[40][41] However, the error handling proposal was eventually abandoned.[42]

In June 2020, a new draft design document[43] was published that would add the necessary syntax to Go for declaring generic functions and types. A code translation tool, go2go, was provided to allow users to try the new syntax, along with a generics-enabled version of the online Go Playground.[44]

Generics were finally added to Go in version 1.18 on March 15, 2022.[45]

Versioning

[edit]

Go 1 guarantees compatibility[46] for the language specification and major parts of the standard library. All versions up through the current Go 1.23 release[47] have maintained this promise.

Go does not follow SemVer; rather, each major Go release is supported until there are two newer major releases. Unlike most software, Go calls the second number in a version the major, i.e., in 1.x x is the major version. [48] This is because Go plans to never reach 2.0, given that compatibility is one of language's major selling points.[49]

Design

[edit]

Go is influenced by C (especially the Plan 9 dialect[50][failed verificationsee discussion]), but with an emphasis on greater simplicity and safety. It consists of:

Syntax

[edit]

Go's syntax includes changes from C aimed at keeping code concise and readable. A combined declaration/initialization operator was introduced that allows the programmer to write i := 3 or s := "Hello, world!", without specifying the types of variables used. This contrasts with C's int i = 3; and const char *s = "Hello, world!";.

Semicolons still terminate statements;[a] but are implicit when the end of a line occurs.[b]

Methods may return multiple values, and returning a result, err pair is the conventional way a method indicates an error to its caller in Go.[c] Go adds literal syntaxes for initializing struct parameters by name and for initializing maps and slices. As an alternative to C's three-statement for loop, Go's range expressions allow concise iteration over arrays, slices, strings, maps, and channels.[58]

fmt.Println("Hello World!") is a statement.

In Go, statements are separated by ending a line (hitting the Enter key) or by a semicolon ";".

Hitting the Enter key adds ";" to the end of the line implicitly (does not show up in the source code).

The left curly bracket { cannot come at the start of a line.[59]

Types

[edit]

Go has a number of built-in types, including numeric ones (byte, int64, float32, etc.), Booleans, and byte strings (string). Strings are immutable; built-in operators and keywords (rather than functions) provide concatenation, comparison, and UTF-8 encoding/decoding.[60] Record types can be defined with the struct keyword.[61]

For each type T and each non-negative integer constant n, there is an array type denoted [n]T; arrays of differing lengths are thus of different types. Dynamic arrays are available as "slices", denoted []T for some type T. These have a length and a capacity specifying when new memory needs to be allocated to expand the array. Several slices may share their underlying memory.[38][62][63]

Pointers are available for all types, and the pointer-to-T type is denoted *T. Address-taking and indirection use the & and * operators, as in C, or happen implicitly through the method call or attribute access syntax.[64][65] There is no pointer arithmetic,[d] except via the special unsafe.Pointer type in the standard library.[66]

For a pair of types K, V, the type map[K]V is the type mapping type-K keys to type-V values, though Go Programming Language specification does not give any performance guarantees or implementation requirements for map types. Hash tables are built into the language, with special syntax and built-in functions. chan T is a channel that allows sending values of type T between concurrent Go processes.[67]

Aside from its support for interfaces, Go's type system is nominal: the type keyword can be used to define a new named type, which is distinct from other named types that have the same layout (in the case of a struct, the same members in the same order). Some conversions between types (e.g., between the various integer types) are pre-defined and adding a new type may define additional conversions, but conversions between named types must always be invoked explicitly.[68] For example, the type keyword can be used to define a type for IPv4 addresses, based on 32-bit unsigned integers as follows:

type ipv4addr uint32

With this type definition, ipv4addr(x) interprets the uint32 value x as an IP address. Simply assigning x to a variable of type ipv4addr is a type error.[69]

Constant expressions may be either typed or "untyped"; they are given a type when assigned to a typed variable if the value they represent passes a compile-time check.[70]

Function types are indicated by the func keyword; they take zero or more parameters and return zero or more values, all of which are typed. The parameter and return values determine a function type; thus, func(string, int32) (int, error) is the type of functions that take a string and a 32-bit signed integer, and return a signed integer (of default width) and a value of the built-in interface type error.[71]

Any named type has a method set associated with it. The IP address example above can be extended with a method for checking whether its value is a known standard:

// ZeroBroadcast reports whether addr is 255.255.255.255.
func (addr ipv4addr) ZeroBroadcast() bool {
    return addr == 0xFFFFFFFF
}

Due to nominal typing, this method definition adds a method to ipv4addr, but not on uint32. While methods have special definition and call syntax, there is no distinct method type.[72]

Interface system

[edit]

Go provides two features that replace class inheritance.[citation needed]

The first is embedding, which can be viewed as an automated form of composition.[73]

The second are its interfaces, which provides runtime polymorphism.[74]: 266  Interfaces are a class of types and provide a limited form of structural typing in the otherwise nominal type system of Go. An object which is of an interface type is also of another type, much like C++ objects being simultaneously of a base and derived class. The design of Go interfaces was inspired by protocols from the Smalltalk programming language.[75] Multiple sources use the term duck typing when describing Go interfaces.[76][77] Although the term duck typing is not precisely defined and therefore not wrong, it usually implies that type conformance is not statically checked. Because conformance to a Go interface is checked statically by the Go compiler (except when performing a type assertion), the Go authors prefer the term structural typing.[78]

The definition of an interface type lists required methods by name and type. Any object of type T for which functions exist matching all the required methods of interface type I is an object of type I as well. The definition of type T need not (and cannot) identify type I. For example, if Shape, Square and Circle are defined as

import "math"

type Shape interface {
    Area() float64
}

type Square struct { // Note: no "implements" declaration
    side float64
}

func (sq Square) Area() float64 { return sq.side * sq.side }

type Circle struct { // No "implements" declaration here either
    radius float64
}

func (c Circle) Area() float64 { return math.Pi * math.Pow(c.radius, 2) }

then both a Square and a Circle are implicitly a Shape and can be assigned to a Shape-typed variable.[74]: 263–268  In formal language, Go's interface system provides structural rather than nominal typing. Interfaces can embed other interfaces with the effect of creating a combined interface that is satisfied by exactly the types that implement the embedded interface and any methods that the newly defined interface adds.[74]: 270 

The Go standard library uses interfaces to provide genericity in several places, including the input/output system that is based on the concepts of Reader and Writer.[74]: 282–283 

Besides calling methods via interfaces, Go allows converting interface values to other types with a run-time type check. The language constructs to do so are the type assertion,[79] which checks against a single potential type:

var shp Shape = Square{5}
square, ok := shp.(Square) // Asserts Square type on shp, should work
if ok {
	fmt.Printf("%#v\n", square)
} else {
	fmt.Println("Can't print shape as Square")
}

and the type switch,[80] which checks against multiple types:[citation needed]

func (sq Square) Diagonal() float64 { return sq.side * math.Sqrt2 }
func (c Circle) Diameter() float64 { return 2 * c.radius }

func LongestContainedLine(shp Shape) float64 {
	switch v := shp.(type) {
	case Square:
		return v.Diagonal() // Or, with type assertion, shp.(Square).Diagonal()
	case Circle:
		return v.Diameter() // Or, with type assertion, shp.(Circle).Diameter()
	default:
		return 0 // In practice, this should be handled with errors
	}
}

The empty interface interface{} is an important base case because it can refer to an item of any concrete type. It is similar to the Object class in Java or C# and is satisfied by any type, including built-in types like int.[74]: 284  Code using the empty interface cannot simply call methods (or built-in operators) on the referred-to object, but it can store the interface{} value, try to convert it to a more useful type via a type assertion or type switch, or inspect it with Go's reflect package.[81] Because interface{} can refer to any value, it is a limited way to escape the restrictions of static typing, like void* in C but with additional run-time type checks.[citation needed]

The interface{} type can be used to model structured data of any arbitrary schema in Go, such as JSON or YAML data, by representing it as a map[string]interface{} (map of string to empty interface). This recursively describes data in the form of a dictionary with string keys and values of any type.[82]

Interface values are implemented using pointer to data and a second pointer to run-time type information.[83] Like some other types implemented using pointers in Go, interface values are nil if uninitialized.[84]

Generic code using parameterized types

[edit]

Since version 1.18, Go supports generic code using parameterized types.[85]

Functions and types now have the ability to be generic using type parameters. These type parameters are specified within square brackets, right after the function or type name.[86] The compiler transforms the generic function or type into non-generic by substituting type arguments for the type parameters provided, either explicitly by the user or type inference by the compiler.[87] This transformation process is referred to as type instantiation.[88]

Interfaces now can define a set of types (known as type set) using | (Union) operator, as well as a set of methods. These changes were made to support type constraints in generics code. For a generic function or type, a constraint can be thought of as the type of the type argument: a meta-type. This new ~T syntax will be the first use of ~ as a token in Go. ~T means the set of all types whose underlying type is T.[89]

type Number interface {
	~int | ~float64 | ~float32 | ~int32 | ~int64
}

func Add[T Number](nums ...T) T {
	var sum T
	for _, v := range nums {
		sum += v
	}
	return sum
}

func main() {
	add := Add[int]             // Type instantiation
	println(add(1, 2, 3, 4, 5)) // 15

	res := Add(1.1, 2.2, 3.3, 4.4, 5.5) // Type Inference
	println(res)                        // +1.650000e+001
}

Enumerated types

[edit]

Go uses the iota keyword to create enumerated constants.[90]

type ByteSize float64

const (
    _           = iota // ignore first value by assigning to blank identifier
    KB ByteSize = 1 << (10 * iota)
    MB
    GB
)

Package system

[edit]

In Go's package system, each package has a path (e.g., "compress/bzip2" or "golang.org/x/net/html") and a name (e.g., bzip2 or html). References to other packages' definitions must always be prefixed with the other package's name, and only the capitalized names from other packages are accessible: io.Reader is public but bzip2.reader is not.[91] The go get command can retrieve packages stored in a remote repository[92] and developers are encouraged to develop packages inside a base path corresponding to a source repository (such as example.com/user_name/package_name) to reduce the likelihood of name collision with future additions to the standard library or other external libraries.[93]

Concurrency: goroutines and channels

[edit]

The Go language has built-in facilities, as well as library support, for writing concurrent programs. Concurrency refers not only to CPU parallelism, but also to asynchrony: letting slow operations like a database or network read run while the program does other work, as is common in event-based servers.[94]

The primary concurrency construct is the goroutine, a type of green thread.[95]: 280–281  A function call prefixed with the go keyword starts a function in a new goroutine. The language specification does not specify how goroutines should be implemented, but current implementations multiplex a Go process's goroutines onto a smaller set of operating-system threads, similar to the scheduling performed in Erlang.[96]: 10 

While a standard library package featuring most of the classical concurrency control structures (mutex locks, etc.) is available,[96]: 151–152  idiomatic concurrent programs instead prefer channels, which send messages between goroutines.[97] Optional buffers store messages in FIFO order[98]: 43  and allow sending goroutines to proceed before their messages are received.[95]: 233 

Channels are typed, so that a channel of type chan T can only be used to transfer messages of type T. Special syntax is used to operate on them; <-ch is an expression that causes the executing goroutine to block until a value comes in over the channel ch, while ch <- x sends the value x (possibly blocking until another goroutine receives the value). The built-in switch-like select statement can be used to implement non-blocking communication on multiple channels; see below for an example. Go has a memory model describing how goroutines must use channels or other operations to safely share data.[99]

The existence of channels does not by itself set Go apart from actor model-style concurrent languages like Erlang, where messages are addressed directly to actors (corresponding to goroutines). In the actor model, channels are themselves actors, therefore addressing a channel just means to address an actor. The actor style can be simulated in Go by maintaining a one-to-one correspondence between goroutines and channels, but the language allows multiple goroutines to share a channel or a single goroutine to send and receive on multiple channels.[96]: 147 

From these tools one can build concurrent constructs like worker pools, pipelines (in which, say, a file is decompressed and parsed as it downloads), background calls with timeout, "fan-out" parallel calls to a set of services, and others.[100] Channels have also found uses further from the usual notion of interprocess communication, like serving as a concurrency-safe list of recycled buffers,[101] implementing coroutines (which helped inspire the name goroutine),[102] and implementing iterators.[103]

Concurrency-related structural conventions of Go (channels and alternative channel inputs) are derived from Tony Hoare's communicating sequential processes model. Unlike previous concurrent programming languages such as Occam or Limbo (a language on which Go co-designer Rob Pike worked),[104] Go does not provide any built-in notion of safe or verifiable concurrency.[105] While the communicating-processes model is favored in Go, it is not the only one: all goroutines in a program share a single address space. This means that mutable objects and pointers can be shared between goroutines; see § Lack of data race safety, below.

Suitability for parallel programming

[edit]

Although Go's concurrency features are not aimed primarily at parallel processing,[94] they can be used to program shared-memory multi-processor machines. Various studies have been done into the effectiveness of this approach.[106] One of these studies compared the size (in lines of code) and speed of programs written by a seasoned programmer not familiar with the language and corrections to these programs by a Go expert (from Google's development team), doing the same for Chapel, Cilk and Intel TBB. The study found that the non-expert tended to write divide-and-conquer algorithms with one go statement per recursion, while the expert wrote distribute-work-synchronize programs using one goroutine per processor core. The expert's programs were usually faster, but also longer.[107]

Lack of data race safety

[edit]

Go's approach to concurrency can be summarized as "don't communicate by sharing memory; share memory by communicating".[108] There are no restrictions on how goroutines access shared data, making data races possible. Specifically, unless a program explicitly synchronizes via channels or other means, writes from one goroutine might be partly, entirely, or not at all visible to another, often with no guarantees about ordering of writes.[105] Furthermore, Go's internal data structures like interface values, slice headers, hash tables, and string headers are not immune to data races, so type and memory safety can be violated in multithreaded programs that modify shared instances of those types without synchronization.[109][110] Instead of language support, safe concurrent programming thus relies on conventions; for example, Chisnall recommends an idiom called "aliases xor mutable", meaning that passing a mutable value (or pointer) over a channel signals a transfer of ownership over the value to its receiver.[96]: 155  The gc toolchain has an optional data race detector that can check for unsynchronized access to shared memory during runtime since version 1.1,[111] additionally a best-effort race detector is also included by default since version 1.6 of the gc runtime for access to the map data type.[112]

Binaries

[edit]

The linker in the gc toolchain creates statically linked binaries by default; therefore all Go binaries include the Go runtime.[113][114]

Omissions

[edit]

Go deliberately omits certain features common in other languages, including (implementation) inheritance, assertions,[e] pointer arithmetic,[d] implicit type conversions, untagged unions,[f] and tagged unions.[g] The designers added only those facilities that all three agreed on.[117]

Of the omitted language features, the designers explicitly argue against assertions and pointer arithmetic, while defending the choice to omit type inheritance as giving a more useful language, encouraging instead the use of interfaces to achieve dynamic dispatch[h] and composition to reuse code. Composition and delegation are in fact largely automated by struct embedding; according to researchers Schmager et al., this feature "has many of the drawbacks of inheritance: it affects the public interface of objects, it is not fine-grained (i.e, no method-level control over embedding), methods of embedded objects cannot be hidden, and it is static", making it "not obvious" whether programmers will overuse it to the extent that programmers in other languages are reputed to overuse inheritance.[73]

Exception handling was initially omitted in Go due to lack of a "design that gives value proportionate to the complexity".[118] An exception-like panic/recover mechanism that avoids the usual try-catch control structure was proposed[119] and released in the March 30, 2010 snapshot.[120] The Go authors advise using it for unrecoverable errors such as those that should halt an entire program or server request, or as a shortcut to propagate errors up the stack within a package.[121][122] Across package boundaries, Go includes a canonical error type, and multi-value returns using this type are the standard idiom.[4]

Style

[edit]

The Go authors put substantial effort into influencing the style of Go programs:

  • Indentation, spacing, and other surface-level details of code are automatically standardized by the gofmt tool. It uses tabs for indentation and blanks for alignment. Alignment assumes that an editor is using a fixed-width font.[123] golint does additional style checks automatically, but has been deprecated and archived by the Go maintainers.[124]
  • Tools and libraries distributed with Go suggest standard approaches to things like API documentation (godoc),[125] testing (go test), building (go build), package management (go get), and so on.
  • Go enforces rules that are recommendations in other languages, for example banning cyclic dependencies, unused variables[126] or imports,[127] and implicit type conversions.
  • The omission of certain features (for example, functional-programming shortcuts like map and Java-style try/finally blocks) tends to encourage a particular explicit, concrete, and imperative programming style.
  • On day one the Go team published a collection of Go idioms,[125] and later also collected code review comments,[128] talks,[129] and official blog posts[130] to teach Go style and coding philosophy.

Tools

[edit]

The main Go distribution includes tools for building, testing, and analyzing code:

  • go build, which builds Go binaries using only information in the source files themselves, no separate makefiles
  • go test, for unit testing and microbenchmarks as well as fuzzing
  • go fmt, for formatting code
  • go install, for retrieving and installing remote packages
  • go vet, a static analyzer looking for potential errors in code
  • go run, a shortcut for building and executing code
  • godoc, for displaying documentation or serving it via HTTP
  • gorename, for renaming variables, functions, and so on in a type-safe way
  • go generate, a standard way to invoke code generators
  • go mod, for creating a new module, adding dependencies, upgrading dependencies, etc.

It also includes profiling and debugging support, fuzzing capabilities to detect bugs, runtime instrumentation (for example, to track garbage collection pauses), and a data race detector.

Another tool maintained by the Go team but is not included in Go distributions is gopls, a language server that provides IDE features such as intelligent code completion to Language Server Protocol compatible editors.[131]

An ecosystem of third-party tools adds to the standard distribution, such as gocode, which enables code autocompletion in many text editors, goimports, which automatically adds/removes package imports as needed, and errcheck, which detects code that might unintentionally ignore errors.

Examples

[edit]

Hello world

[edit]
package main

import "fmt"

func main() {
    fmt.Println("hello world")
}

where "fmt" is the package for formatted I/O, similar to C's C file input/output.[132]

Concurrency

[edit]

The following simple program demonstrates Go's concurrency features to implement an asynchronous program. It launches two lightweight threads ("goroutines"): one waits for the user to type some text, while the other implements a timeout. The select statement waits for either of these goroutines to send a message to the main routine, and acts on the first message to arrive (example adapted from David Chisnall's book).[96]: 152 

package main

import (
    "fmt"
    "time"
)

func readword(ch chan string) {
    fmt.Println("Type a word, then hit Enter.")
    var word string
    fmt.Scanf("%s", &word)
    ch <- word
}

func timeout(t chan bool) {
    time.Sleep(5 * time.Second)
    t <- false
}

func main() {
    t := make(chan bool)
    go timeout(t)

    ch := make(chan string)
    go readword(ch)

    select {
    case word := <-ch:
        fmt.Println("Received", word)
    case <-t:
        fmt.Println("Timeout.")
    }
}

Testing

[edit]

The testing package provides support for automated testing of go packages.[133] Target function example:

func ExtractUsername(email string) string {
	at := strings.Index(email, "@")
	return email[:at]
}

Test code (note that assert keyword is missing in Go; tests live in <filename>_test.go at the same package):

import (
    "testing"
)

func TestExtractUsername(t *testing.T) {
	t.Run("withoutDot", func(t *testing.T) {
		username := ExtractUsername("r@google.com")
		if username != "r" {
			t.Fatalf("Got: %v\n", username)
		}
	})

	t.Run("withDot", func(t *testing.T) {
		username := ExtractUsername("jonh.smith@example.com")
		if username != "jonh.smith" {
			t.Fatalf("Got: %v\n", username)
		}
	})
}

It is possible to run tests in parallel.

Web app

[edit]

The net/http[134] package provides support for creating web applications.

This example would show "Hello world!" when localhost:8080 is visited.

package main

import (
    "fmt"
    "log"
    "net/http"
)

func helloFunc(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello world!")
}

func main() {
    http.HandleFunc("/", helloFunc)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

Applications

[edit]

Go has found widespread adoption in various domains due to its robust standard library and ease of use.[135]

Popular applications include: Caddy, a web server that automates the process of setting up HTTPS,[136] Docker, which provides a platform for containerization, aiming to ease the complexities of software development and deployment,[137] Kubernetes, which automates the deployment, scaling, and management of containerized applications,[138] CockroachDB, a distributed SQL database engineered for scalability and strong consistency,[139] and Hugo, a static site generator that prioritizes speed and flexibility, allowing developers to create websites efficiently.[140]

Reception

[edit]

The interface system, and the deliberate omission of inheritance, were praised by Michele Simionato, who likened these characteristics to those of Standard ML, calling it "a shame that no popular language has followed [this] particular route".[141]

Dave Astels at Engine Yard wrote in 2009:[142]

Go is extremely easy to dive into. There are a minimal number of fundamental language concepts and the syntax is clean and designed to be clear and unambiguous. Go is still experimental and still a little rough around the edges.

Go was named Programming Language of the Year by the TIOBE Programming Community Index in its first year, 2009, for having a larger 12-month increase in popularity (in only 2 months, after its introduction in November) than any other language that year, and reached 13th place by January 2010,[143] surpassing established languages like Pascal. By June 2015, its ranking had dropped to below 50th in the index, placing it lower than COBOL and Fortran.[144] But as of January 2017, its ranking had surged to 13th, indicating significant growth in popularity and adoption. Go was again awarded TIOBE Programming Language of the Year in 2016.[145]

Bruce Eckel has stated:[146]

The complexity of C++ (even more complexity has been added in the new C++), and the resulting impact on productivity, is no longer justified. All the hoops that the C++ programmer had to jump through in order to use a C-compatible language make no sense anymore -- they're just a waste of time and effort. Go makes much more sense for the class of problems that C++ was originally intended to solve.

A 2011 evaluation of the language and its gc implementation in comparison to C++ (GCC), Java and Scala by a Google engineer found:

Go offers interesting language features, which also allow for a concise and standardized notation. The compilers for this language are still immature, which reflects in both performance and binary sizes.

— R. Hundt[147]

The evaluation got a rebuttal from the Go development team. Ian Lance Taylor, who had improved the Go code for Hundt's paper, had not been aware of the intention to publish his code, and says that his version was "never intended to be an example of idiomatic or efficient Go"; Russ Cox then optimized the Go code, as well as the C++ code, and got the Go code to run almost as fast as the C++ version and more than an order of magnitude faster than the code in the paper.[148]

  • Go's nil combined with the lack of algebraic types leads to difficulty handling failures and base cases.[149][150]
  • Go does not allow an opening brace to appear on its own line, which forces all Go programmers to use the same brace style.[151]
  • Go has been criticized for focusing on simplicity of implementation rather than correctness and flexibility; as an example, the language uses POSIX file semantics on all platforms, and therefore provides incorrect information on platforms such as Windows (which do not follow the aforementioned standard).[152][153]
  • A study showed that it is as easy to make concurrency bugs with message passing as with shared memory, sometimes even more.[154]

Naming dispute

[edit]

On November 10, 2009, the day of the general release of the language, Francis McCabe, developer of the Go! programming language (note the exclamation point), requested a name change of Google's language to prevent confusion with his language, which he had spent 10 years developing.[155] McCabe raised concerns that "the 'big guy' will end up steam-rollering over" him, and this concern resonated with the more than 120 developers who commented on Google's official issues thread saying they should change the name, with some[156] even saying the issue contradicts Google's motto of: Don't be evil.[157]

On October 12, 2010, the filed public issue ticket was closed by Google developer Russ Cox (@rsc) with the custom status "Unfortunate" accompanied by the following comment:

"There are many computing products and services named Go. In the 11 months since our release, there has been minimal confusion of the two languages."[157]

See also

[edit]

Notes

[edit]
  1. ^ But "To allow complex statements to occupy a single line, a semicolon may be omitted before a closing ) or }".[56]
  2. ^ "if the newline comes after a token that could end a statement, [the lexer will] insert a semicolon".[57]
  3. ^ Usually, exactly one of the result and error values has a value other than the type's zero value; sometimes both do, as when a read or write can only be partially completed, and sometimes neither, as when a read returns 0 bytes. See Semipredicate problem: Multivalued return.
  4. ^ a b Language FAQ "Why is there no pointer arithmetic? Safety ... never derive an illegal address that succeeds incorrectly ... using array indices can be as efficient as ... pointer arithmetic ... simplify the implementation of the garbage collector...."[4]
  5. ^ Language FAQ "Why does Go not have assertions? ...our experience has been that programmers use them as a crutch to avoid thinking about proper error handling and reporting...."[4]
  6. ^ Language FAQ "Why are there no untagged unions...? [they] would violate Go's memory safety guarantees."[4]
  7. ^ Language FAQ "Why does Go not have variant types? ... We considered [them but] they overlap in confusing ways with interfaces.... [S]ome of what variant types address is already covered, ... although not as elegantly."[4] (The tag of an interface type[115] is accessed with a type assertion[116]).
  8. ^ Questions "How do I get dynamic dispatch of methods?" and "Why is there no type inheritance?" in the language FAQ.[4]

References

[edit]
  1. ^ "Codewalk: First-Class Functions in Go". Go supports first class functions, higher-order functions, user-defined function types, function literals, closures, and multiple return values. This rich feature set supports a functional programming style in a strongly typed language.
  2. ^ "Is Go an object-oriented language?". Retrieved April 13, 2019. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy.
  3. ^ "Go: code that grows with grace". Retrieved June 24, 2018. Go is Object Oriented, but not in the usual way.
  4. ^ a b c d e f g h "Language Design FAQ". The Go Programming Language. January 16, 2010. Retrieved February 27, 2010.
  5. ^ a b "Text file LICENSE". The Go Programming Language. Retrieved October 5, 2012.
  6. ^ "The Go Programming Language Specification - the Go Programming Language".
  7. ^ a b "Why doesn't Go have "implements" declarations?". The Go Programming Language. Retrieved October 1, 2015.
  8. ^ Pike, Rob (December 22, 2014). "Rob Pike on Twitter". Archived from the original on April 7, 2022. Retrieved March 13, 2016. Go has structural typing, not duck typing. Full interface satisfaction is checked and required.
  9. ^ "lang/go: go-1.4". OpenBSD ports. December 23, 2014. Retrieved January 19, 2015.
  10. ^ "Go Porting Efforts". Go Language Resources. cat-v. January 12, 2010. Retrieved January 18, 2010.
  11. ^ "Additional IP Rights Grant". The Go Programming Language. Retrieved October 5, 2012.
  12. ^ "Go Introduction". www.w3schools.com. Retrieved November 23, 2024.
  13. ^ "Go Introduction". www.w3schools.com. Retrieved November 23, 2024.
  14. ^ Kincaid, Jason (November 10, 2009). "Google's Go: A New Programming Language That's Python Meets C++". TechCrunch. Retrieved January 18, 2010.
  15. ^ Metz, Cade (May 5, 2011). "Google Go boldly goes where no code has gone before". The Register.
  16. ^ "Is the language called Go or Golang?". Retrieved March 16, 2022. The language is called Go.
  17. ^ "Go 1.5 Release Notes". Retrieved January 28, 2016. The compiler and runtime are now implemented in Go and assembler, without C.
  18. ^ "The Go programming language". Retrieved November 1, 2024.
  19. ^ "gofrontend". Retrieved November 1, 2024.
  20. ^ "gccgo". Retrieved November 1, 2024. gccgo, the GNU compiler for the Go programming language
  21. ^ "Gollvm". Retrieved November 1, 2024. Gollvm is an LLVM-based Go compiler.
  22. ^ "A compiler from Go to JavaScript for running Go code in a browser: Gopherjs/Gopherjs". GitHub. Archived from the original on December 12, 2023.
  23. ^ "Go at Google: Language Design in the Service of Software Engineering". Retrieved October 8, 2018.
  24. ^ Pike, Rob (April 28, 2010). "Another Go at Language Design". Stanford EE Computer Systems Colloquium. Stanford University. Video available.
  25. ^ "Frequently Asked Questions (FAQ) - The Go Programming Language". The Go Programming Language. Retrieved February 26, 2016.
  26. ^ Binstock, Andrew (May 18, 2011). "Dr. Dobb's: Interview with Ken Thompson". Archived from the original on January 5, 2013. Retrieved February 7, 2014.
  27. ^ Pike, Rob (2012). "Less is exponentially more".
  28. ^ Griesemer, Robert (2015). "The Evolution of Go".
  29. ^ Griesemer, Robert; Pike, Rob; Thompson, Ken; Taylor, Ian; Cox, Russ; Kim, Jini; Langley, Adam. "Hey! Ho! Let's Go!". Google Open Source. Retrieved May 17, 2018.
  30. ^ Shankland, Stephen (March 30, 2012). "Google's Go language turns one, wins a spot at YouTube: The lower-level programming language has matured enough to sport the 1.0 version number. And it's being used for real work at Google". News. CNet. CBS Interactive Inc. Retrieved August 6, 2017. Google has released version 1 of its Go programming language, an ambitious attempt to improve upon giants of the lower-level programming world such as C and C++.
  31. ^ "Release History". The Go Programming Language.
  32. ^ "Go FAQ: Is Google using Go internally?". Retrieved March 9, 2013.
  33. ^ "The Go Gopher - The Go Programming Language". go.dev. Retrieved February 9, 2023.
  34. ^ "Go fonts". Go. November 16, 2016. Retrieved March 12, 2019.
  35. ^ "Go Font TTFs". GitHub. Retrieved April 2, 2019.
  36. ^ "Go's New Brand". The Go Blog. Retrieved November 9, 2018.
  37. ^ Merrick, Alice (March 9, 2021). "Go Developer Survey 2020 Results". Go Programming Language. Retrieved March 16, 2022.
  38. ^ a b Pike, Rob (September 26, 2013). "Arrays, slices (and strings): The mechanics of 'append'". The Go Blog. Retrieved March 7, 2015.
  39. ^ "E2E: Erik Meijer and Robert Griesemer". Channel 9. Microsoft. May 7, 2012.
  40. ^ "Go 2 Draft Designs". Retrieved September 12, 2018.
  41. ^ "The Go Blog: Go 2 Draft Designs". August 28, 2018.
  42. ^ "Proposal: A built-in Go error check function, "try"". Go repository on GitHub. Retrieved March 16, 2022.
  43. ^ "Type Parameters — Draft Design". go.googlesource.com.
  44. ^ "Generics in Go". bitfieldconsulting.com. December 17, 2021.
  45. ^ "Go 1.18 is released!". Go Programming Language. March 15, 2022. Retrieved March 16, 2022.
  46. ^ "Go 1 and the Future of Go Programs". The Go Programming Language.
  47. ^ "Go 1.23 Release Notes". The Go Programming Language.
  48. ^ "Release History". The Go Programming Language.
  49. ^ "Backward Compatibility, Go 1.21, and Go 2". The Go Programming Language.
  50. ^ "A Quick Guide to Go's Assembler". go.dev. Retrieved December 31, 2021.
  51. ^ Pike, Rob. "The Go Programming Language". YouTube. Retrieved July 1, 2011.
  52. ^ Pike, Rob (November 10, 2009). The Go Programming Language (flv) (Tech talk). Google. Event occurs at 8:53.
  53. ^ "Download and install packages and dependencies". See godoc.org for addresses and documentation of some packages.
  54. ^ "GoDoc". godoc.org.
  55. ^ Pike, Rob. "The Changelog" (Podcast). Archived from the original on October 20, 2013. Retrieved October 7, 2013.
  56. ^ "Go Programming Language Specification, §Semicolons". The Go Programming Language.
  57. ^ "Effective Go, §Semicolons". The Go Programming Language.
  58. ^ "The Go Programming Language Specification". The Go Programming Language.
  59. ^ "Go Syntax". www.w3schools.com. Retrieved November 23, 2024.
  60. ^ Pike, Rob (October 23, 2013). "Strings, bytes, runes and characters in Go".
  61. ^ Doxsey, Caleb. "Structs and Interfaces — An Introduction to Programming in Go". www.golang-book.com. Retrieved October 15, 2018.
  62. ^ Gerrand, Andrew. "Go Slices: usage and internals".
  63. ^ The Go Authors. "Effective Go: Slices".
  64. ^ The Go authors. "Selectors".
  65. ^ The Go authors. "Calls".
  66. ^ "Go Programming Language Specification, §Package unsafe". The Go Programming Language.
  67. ^ "The Go Programming Language Specification". go.dev. Retrieved December 31, 2021.
  68. ^ "The Go Programming Language Specification". The Go Programming Language.
  69. ^ "A tour of go". go.dev.
  70. ^ "The Go Programming Language Specification". The Go Programming Language.
  71. ^ "The Go Programming Language Specification". go.dev. Retrieved December 31, 2021.
  72. ^ "The Go Programming Language Specification". The Go Programming Language.
  73. ^ a b Schmager, Frank; Cameron, Nicholas; Noble, James (2010). GoHotDraw: evaluating the Go programming language with design patterns. Evaluation and Usability of Programming Languages and Tools. ACM.
  74. ^ a b c d e Balbaert, Ivo (2012). The Way to Go: A Thorough Introduction to the Go Programming Language. iUniverse.
  75. ^ "The Evolution of Go". talks.golang.org. Retrieved March 13, 2016.
  76. ^ Diggins, Christopher (November 24, 2009). "Duck Typing and the Go Programming Language". Dr. Dobb's, The world of software development. Retrieved March 10, 2016.
  77. ^ Ryer, Mat (December 1, 2015). "Duck typing in Go". Retrieved March 10, 2016.
  78. ^ "Frequently Asked Questions (FAQ) - The Go Programming Language". The Go Programming Language.
  79. ^ "The Go Programming Language Specification". The Go Programming Language.
  80. ^ "The Go Programming Language Specification". The Go Programming Language.
  81. ^ "reflect package". pkg.go.dev.
  82. ^ "map[string]interface{} in Go". bitfieldconsulting.com. June 6, 2020.
  83. ^ "Go Data Structures: Interfaces". Retrieved November 15, 2012.
  84. ^ "The Go Programming Language Specification". The Go Programming Language.
  85. ^ "Go 1.18 Release Notes: Generics". Go Programming Language. March 15, 2022. Retrieved March 16, 2022.
  86. ^ "Type Parameters Proposal". go.googlesource.com. Retrieved June 25, 2023.
  87. ^ "The Go Programming Language Specification - The Go Programming Language". go.dev. Retrieved June 25, 2023.
  88. ^ "An Introduction To Generics - The Go Programming Language". go.dev. Retrieved June 25, 2023.
  89. ^ "Type Parameters Proposal". go.googlesource.com. Retrieved June 25, 2023.
  90. ^ "Effective Go". golang.org. The Go Authors. Retrieved May 13, 2014.
  91. ^ "A Tutorial for the Go Programming Language". The Go Programming Language. Retrieved March 10, 2013. In Go the rule about visibility of information is simple: if a name (of a top-level type, function, method, constant or variable, or of a structure field or method) is capitalized, users of the package may see it. Otherwise, the name and hence the thing being named is visible only inside the package in which it is declared.
  92. ^ "go". The Go Programming Language.
  93. ^ "How to Write Go Code". The Go Programming Language. The packages from the standard library are given short import paths such as "fmt" and "net/http". For your own packages, you must choose a base path that is unlikely to collide with future additions to the standard library or other external libraries. If you keep your code in a source repository somewhere, then you should use the root of that source repository as your base path. For instance, if you have an Example account at example.com/user, that should be your base path
  94. ^ a b Pike, Rob (September 18, 2012). "Concurrency is not Parallelism".
  95. ^ a b Donovan, Alan A. A.; Kernighan, Brian W. (2016). The Go programming language. Addison-Wesley professional computing series. New York, Munich: Addison-Wesley. ISBN 978-0-13-419044-0.
  96. ^ a b c d e Chisnall, David (2012). The Go Programming Language Phrasebook. Addison-Wesley. ISBN 9780132919005.
  97. ^ "Effective Go". The Go Programming Language.
  98. ^ Summerfield, Mark (2012). Programming in Go: Creating Applications for the 21st Century. Addison-Wesley.
  99. ^ "The Go Memory Model". Retrieved April 10, 2017.
  100. ^ "Go Concurrency Patterns". The Go Programming Language.
  101. ^ Graham-Cumming, John (August 24, 2013). "Recycling Memory Buffers in Go".
  102. ^ "tree.go".
  103. ^ Cheslack-Postava, Ewen. "Iterators in Go".
  104. ^ Kernighan, Brian W. "A Descent Into Limbo".
  105. ^ a b "The Go Memory Model". Retrieved January 5, 2011.
  106. ^ Tang, Peiyi (2010). Multi-core parallel programming in Go (PDF). Proc. First International Conference on Advanced Computing and Communications. Archived from the original (PDF) on September 9, 2016. Retrieved May 14, 2015.
  107. ^ Nanz, Sebastian; West, Scott; Soares Da Silveira, Kaue. Examining the expert gap in parallel programming (PDF). Euro-Par 2013. CiteSeerX 10.1.1.368.6137.
  108. ^ Go Authors. "Share Memory By Communicating".
  109. ^ Cox, Russ. "Off to the Races".
  110. ^ Pike, Rob (October 25, 2012). "Go at Google: Language Design in the Service of Software Engineering". Google, Inc. "There is one important caveat: Go is not purely memory safe in the presence of concurrency."
  111. ^ "Introducing the Go Race Detector". The Go Blog. Retrieved June 26, 2013.
  112. ^ "Go 1.6 Release Notes - The Go Programming Language". go.dev. Retrieved November 17, 2023.
  113. ^ "Frequently Asked Questions (FAQ) - the Go Programming Language".
  114. ^ "A Story of a Fat Go Binary". September 21, 2018.
  115. ^ "Go Programming Language Specification, §Interface types". The Go Programming Language.
  116. ^ "Go Programming Language Specification, §Type assertions". The Go Programming Language.
  117. ^ "All Systems Are Go". informIT (Interview). August 17, 2010. Retrieved June 21, 2018.
  118. ^ "Language Design FAQ". November 13, 2009. Archived from the original on November 13, 2009.
  119. ^ "Proposal for an exception-like mechanism". golang-nuts. March 25, 2010. Retrieved March 25, 2010.
  120. ^ "Weekly Snapshot History". The Go Programming Language.
  121. ^ "Panic And Recover". Go wiki.
  122. ^ "Effective Go". The Go Programming Language.
  123. ^ "gofmt". The Go Programming Language. Retrieved February 5, 2021.
  124. ^ "golang/lint public archive". github.com. November 30, 2022.
  125. ^ a b "Effective Go". The Go Programming Language.
  126. ^ "Unused local variables". yourbasic.org. Retrieved February 11, 2021.
  127. ^ "Unused package imports". yourbasic.org. Retrieved February 11, 2021.
  128. ^ "Code Review Comments". GitHub. Retrieved July 3, 2018.
  129. ^ "Talks". Retrieved July 3, 2018.
  130. ^ "Errors Are Values". Retrieved July 3, 2018.
  131. ^ "tools/gopls/README.md at master · golang/tools". GitHub. Retrieved November 17, 2023.
  132. ^ "fmt". The Go Programming Language. Retrieved April 8, 2019.
  133. ^ "testing". The Go Programming Language. Retrieved December 27, 2020.
  134. ^ "http package - net/http - Go Packages". pkg.go.dev. Retrieved November 23, 2024.
  135. ^ Lee, Wei-Meng (November 24, 2022). "Introduction to the Go Programming Language". Component Developer Magazine. Archived from the original on June 5, 2023. Retrieved September 8, 2023.
  136. ^ Hoffmann, Frank; Neumeyer, Mandy (August 2018). "Simply Secure". Linux Magazine. No. 213. Archived from the original on May 28, 2023. Retrieved September 8, 2023.
  137. ^ Lee, Wei-Meng (August 31, 2022). "Introduction to Containerization Using Docker". CODE Magazine. Archived from the original on May 30, 2023. Retrieved September 8, 2023.
  138. ^ Pirker, Alexander (February 24, 2023). "Kubernetes Security for Starters". CODE Magazine. Archived from the original on April 1, 2023. Retrieved September 8, 2023.
  139. ^ Taft, Rebecca; Sharif, Irfan; Matei, Andrei; Van Benschoten, Nathan; Lewis, Jordan; Grieger, Tobias; Niemi, Kai; Woods, Andy; Birzin, Anne; Poss, Raphael; Bardea, Paul; Ranade, Amruta; Darnell, Ben; Gruneir, Bram; Jaffray, Justin; Zhang, Lucy; Mattis, Peter (June 11, 2020). "CockroachDB: The Resilient Geo-Distributed SQL Database". Proceedings of the 2020 ACM SIGMOD International Conference on Management of Data. SIGMOD '20. pp. 1493–1509. doi:10.1145/3318464.3386134. ISBN 978-1-4503-6735-6.
  140. ^ Hopkins, Brandon (September 13, 2022). "Static Site Generation with Hugo". Linux Journal. Archived from the original on April 8, 2023. Retrieved September 8, 2023.
  141. ^ Simionato, Michele (November 15, 2009). "Interfaces vs Inheritance (or, watch out for Go!)". artima. Retrieved November 15, 2009.
  142. ^ Astels, Dave (November 9, 2009). "Ready, Set, Go!". engineyard. Archived from the original on October 19, 2018. Retrieved November 9, 2009.
  143. ^ jt (January 11, 2010). "Google's Go Wins Programming Language Of The Year Award". jaxenter. Retrieved December 5, 2012.
  144. ^ "TIOBE Programming Community Index for June 2015". TIOBE Software. June 2015. Retrieved July 5, 2015.
  145. ^ "TIOBE Index". TIOBE. Retrieved July 15, 2024.
  146. ^ Eckel, Bruce (August 27, 2011). "Calling Go from Python via JSON-RPC". Retrieved August 29, 2011.
  147. ^ Hundt, Robert (2011). Loop recognition in C++/Java/Go/Scala (PDF). Scala Days.
  148. ^ Metz, Cade (July 1, 2011). "Google Go strikes back with C++ bake-off". The Register.
  149. ^ Yager, Will. "Why Go is not Good". Retrieved November 4, 2018.
  150. ^ Dobronszki, Janos. "Everyday Hassles in Go". Retrieved November 4, 2018.
  151. ^ "Why are there braces but no semicolons? And why can't I put the opening brace on the next line?". Retrieved March 26, 2020. The advantages of a single, programmatically mandated format for all Go programs greatly outweigh any perceived disadvantages of the particular style.
  152. ^ "I want off Mr. Golang's Wild Ride". February 28, 2020. Retrieved November 17, 2020.
  153. ^ "proposal: os: Create/Open/OpenFile() set FILE_SHARE_DELETE on windows #32088". GitHub. May 16, 2019. Retrieved November 17, 2020.
  154. ^ Tu, Tengfei (2019). "Understanding Real-World Concurrency Bugs in Go" (PDF). For example, around 58% of blocking bugs are caused by message passing. In addition to the violation of Go's channel usage rules (e.g., waiting on a channel that no one sends data to or close), many concurrency bugs are caused by the mixed usage of message passing and other new semantics and new libraries in Go, which can easily be overlooked but hard to detect
  155. ^ Brownlee, John (November 13, 2009). "Google didn't google "Go" before naming their programming language'". Archived from the original on December 8, 2015. Retrieved May 26, 2016.
  156. ^ Claburn, Thomas (November 11, 2009). "Google 'Go' Name Brings Accusations Of Evil'". InformationWeek. Archived from the original on July 22, 2010. Retrieved January 18, 2010.
  157. ^ a b "Issue 9 - go — I have already used the name for *MY* programming language". Github. Google Inc. Retrieved October 12, 2010.

Further reading

[edit]
[edit]