Wiki data import from Google Code

Andrew Gerrand 2014-12-10 11:35:11 +11:00
commit 5bc444d13c
83 changed files with 7925 additions and 0 deletions

104
Articles.md Normal file

@ -0,0 +1,104 @@
# English
## General
* [Go: A New Language for a New Year](http://kylelemons.net/2012/01/go-new-language-new-year/) _2012-01-06_
* [Why you PHP guys should learn Golang](http://www.mikespook.com/2012/08/why-you-php-guys-should-learn-golang/) _2012-08-10_
* [Why I went from Python to Go (and not node.js)](http://jordanorelli.tumblr.com/post/31533769172/why-i-went-from-python-to-go-and-not-node-js) _2012-09-14_
* [Why I program in Go](http://tech.t9i.in/2013/01/why-program-in-go/) _2013-01-05_
* [What I Love About Go](http://blog.natefinch.com/2013/01/what-i-love-about-go.html) _2013-01-25_
* [Google Go: The Good, the Bad, and the Meh](http://blog.carlsensei.com/post/42828735125) _2013-02-10_
* [Switching from Python to Go](https://www.spacemonkey.com/blog/posts/go-space-monkey) _2014-04-21_
## Concurrency / Channels
* [Concurrent Idioms #1: Broadcasting values in Go with linked channels](http://rogpeppe.wordpress.com/2009/12/01/concurrent-idioms-1-broadcasting-values-in-go-with-linked-channels/) _2009-12-01_
* [Unlimited Buffering with Low Overhead](http://rogpeppe.wordpress.com/2010/02/10/unlimited-buffering-with-low-overhead/) _2010-02-10_
* [Golang: Funny Play with Channel](http://www.mikespook.com/2012/05/golang-funny-play-with-channel/) _2012-05-25_
* [Stacked channels](http://gowithconfidence.tumblr.com/post/31426832143/stacked-channels) _2012-09-12_
* [Just muxing about](http://gowithconfidence.tumblr.com/post/31431608488/muxing) _2012-09-12_
* [applied mux()ing: a LimitBuffer](http://gowithconfidence.tumblr.com/post/31797884887/limit-buffers) _2012-09-18_
* [Fundamentals of concurrent programming](http://www.nada.kth.se/~snilsson/concurrency/) _2013-01-27_
## Interfaces / OOP
* [no methods on interfaces](http://gowithconfidence.tumblr.com/post/31735316104/interface-methods) _2012-09-17_
* [How to use interfaces in Go](http://jordanorelli.tumblr.com/post/32665860244/how-to-use-interfaces-in-go) _2012-10-01_
* [Go Object Oriented Design](http://nathany.com/good) _2013-01-14_
* [It is ridiculously easy to refactor Go](http://www.onebigfluke.com/2013/01/it-is-ridiculously-easy-to-refactor-go.html) _2013-01-27_
* [Functional Iteration in Go](http://hackthology.com/functional-iteration-in-go.html) _2013-12-13_
## Web Development
* [Auth and Sessions](http://shadynasty.biz/blog/2012/09/05/auth-and-sessions/) _2012-09-05_
* [Painless Web Handlers in Go](http://shadynasty.biz/blog/2012/08/07/painless-web-handlers-in-go/) _2012-08-07_
* [Implementing Chat with WebSockets](http://gary.beagledreams.com/page/go-websocket-chat.html) _2012-03-22_
## Misc
* [Zero Downtime upgrades of TCP servers in Go](http://blog.nella.org/?p=879) _2012-05-29_
* [Using the Go Regexp Package](http://blog.kamilkisiel.net/blog/2012/07/05/using-the-go-regexp-package/) _2012-07-05_
* [Function Call by Name in Golang](http://www.mikespook.com/2012/07/function-call-by-name-in-golang/) _2012-07-05_
* [An introduction to cross compilation with Go](http://dave.cheney.net/2012/09/08/an-introduction-to-cross-compilation-with-go) _2012-09-08_
* [Applying The Clean Architecture to Go applications](http://manuel.kiessling.net/2012/09/28/applying-the-clean-architecture-to-go-applications/) _2012-09-08_
* [Methods as Objects in Go](http://ernestmicklei.com/2012/11/26/methods-as-objects-in-go/) _2012-12-26_
* [Optimizing Real World Go](http://bpowers.github.com/weblog/2013/01/05/optimizing-real-world-go/) _2013-01-05_
* [Go-spew: A Journey into Dumping Go Data Structures](https://blog.cyphertite.com/go-spew-a-journey-into-dumping-go-data-structures/) _2013-01-09_
* [I2C Programming in Go](http://www.gmcbay.com/2013/01/i2c-programming-in-go/) _2013-01-12_
* [Function Types in Go (golang)](http://jordanorelli.tumblr.com/post/42369331748/function-types-in-go-golang) _2013-02-05_
* [Go & Assembly](http://www.doxsey.net/blog/go-and-assembly) _2013-02-05_
* [State machines in Go (#golang)](http://denis.papathanasiou.org/?p=1190) _2013-02-10_
* [Go Reflection Codex](http://jimmyfrasche.github.io/go-reflection-codex/)
# Chinese
* [How to write Go code](http://chenxiaoyu.org/2012/03/14/howto-write-golang-code.html)
* [Test Go module](http://chenxiaoyu.org/2012/12/07/golang-module-test-benchmark.html)
* [Build web application with golang](https://github.com/astaxie/build-web-application-with-golang)
* [Go语言评估报告](https://docs.google.com/document/d/1NosYIbM6tfBqKh49BrHOngBfXuT1MfrvYXwc_ikwuMk/edit)
* [Why you PHP guys should learn Golang](http://www.mikespook.com/2012/08/%e4%b8%ba%e4%bb%80%e4%b9%88phper%e5%ba%94%e5%bd%93%e5%ad%a6%e4%b9%a0golang/)
* [Function Call by Name in Golang](http://www.mikespook.com/2012/07/%e5%9c%a8-golang-%e4%b8%ad%e7%94%a8%e5%90%8d%e5%ad%97%e8%b0%83%e7%94%a8%e5%87%bd%e6%95%b0/)
* [Golang: Funny Play with Channel](http://www.mikespook.com/2012/06/golang-channel-%e6%9c%89%e8%b6%a3%e7%9a%84%e5%ba%94%e7%94%a8/)
* [Using MyMySQL - A interface of database/sql](http://www.mikespook.com/2012/05/mymysql-%e7%9a%84-databasesql-%e6%8e%a5%e5%8f%a3%e4%bd%bf%e7%94%a8/)
* [Go did What on the Stack?](http://www.mikespook.com/2011/03/go%e5%9c%a8stack%e4%b8%8a%e5%b9%b2%e4%ba%86%e7%a5%9e%e9%a9%ac%ef%bc%9f/)
* [Gobs on the wire (Translation)](http://www.mikespook.com/2011/03/%e7%bf%bb%e8%af%91%e9%a3%9e%e7%bf%94%e7%9a%84-gob/)
* [Go Environment Setup (Translation)](http://www.mikespook.com/2012/02/%E7%BF%BB%E8%AF%91go-%E7%8E%AF%E5%A2%83%E8%AE%BE%E7%BD%AE/)
* [Error Handling and Go (Translation)](http://www.mikespook.com/2011/08/%E9%94%99%E8%AF%AF%E5%A4%84%E7%90%86%E5%92%8Cgo/)
* [The Go Tool (Translation)](http://www.mikespook.com/2012/02/%E7%BF%BB%E8%AF%91go-%E5%B7%A5%E5%85%B7/)
* [Less is exponentially more (Translation)](http://www.mikespook.com/2012/06/%E7%BF%BB%E8%AF%91%E5%B0%91%E6%98%AF%E6%8C%87%E6%95%B0%E7%BA%A7%E7%9A%84%E5%A4%9A/)
* [Zero Downtime upgrades of TCP servers in Go (Translation)](http://www.mikespook.com/2012/05/%E7%BF%BB%E8%AF%91%E7%94%A8-go-%E5%AE%9E%E7%8E%B0%E9%9B%B6%E5%81%9C%E6%9C%BA%E5%8D%87%E7%BA%A7-tcp-%E6%9C%8D%E5%8A%A1/)
* [雨痕的Go语言学习笔记](https://github.com/qyuhen/book/raw/master/Go%20%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.pdf)
* [Ready? Go! 上篇:大道至简](http://monnand.me/p/ready-go-1/zhCN/)
* [Ready? Go! 下篇:多核并起](http://monnand.me/p/ready-go-2/zhCN/)
# Czech
* [Google Go - 1st birthday](http://www.abclinuxu.cz/clanky/google-go-1.-narozeniny)
* [Google Go - what we find in the kit](http://www.abclinuxu.cz/clanky/google-go-co-najdeme-ve-stavebnici)
* [Google Go - advanced topics](http://www.abclinuxu.cz/clanky/google-go-pokrocilejsi-temata)
* [Google Go by examples I.](http://www.abclinuxu.cz/clanky/google-go-v-prikladech-1)
* [Google Go by examples II.](http://www.abclinuxu.cz/clanky/google-go-v-prikladech-2)
* [Error handling in Go](http://www.abclinuxu.cz/clanky/osetrovani-chyb-v-go)
* [Google Go - The Laws of Reflection](http://www.abclinuxu.cz/clanky/google-go-pravidla-reflexe)
* [Google Go - 2nd birthday](http://www.abclinuxu.cz/clanky/google-go-2.-narozeniny)
# German
* [Go Cheat Sheet - Kurzreferenz für GoLang](http://www.weltchecker.de/go-cheat-sheet-kurzreferenz-fur-golang/) _2011-02-25_
* [Programmiersprachen im Multicore Zeitalter - Google GO und Nebenläufigkeit](http://ps.informatik.uni-siegen.de/downloads/Seminare/multicore-ws2011/donner.pdf) ` [PDF] ` _2012-02-02_
* [A list of German press articles about Go](http://www.hweidner.de/redmine/projects/pub/wiki/Golang_Presse)
# Japanese
* [WindowsでGo言語のまとめ](http://esten.wankuma.com/)
* [Websocketを使ってみた with Go言語](http://u.hinoichi.net/2012/12/14/websocket%E3%82%92%E4%BD%BF%E3%81%A3%E3%81%A6%E3%81%BF%E3%81%9F-with-go%E8%A8%80%E8%AA%9E/)
* [方向のあるチャネルを試す@Go言語](http://u.hinoichi.net/2012/12/29/%E6%96%B9%E5%90%91%E3%81%AE%E3%81%82%E3%82%8B%E3%83%81%E3%83%A3%E3%83%8D%E3%83%AB%E3%82%92%E8%A9%A6%E3%81%99-go%E8%A8%80%E8%AA%9E/)
* [Go言語のチャネルを使った簡単なサンプル -タイムアウト処理-](http://u.hinoichi.net/2012/12/26/go%E8%A8%80%E8%AA%9E%E3%81%AE%E3%83%81%E3%83%A3%E3%83%8D%E3%83%AB%E3%82%92%E4%BD%BF%E3%81%A3%E3%81%9F%E7%B0%A1%E5%8D%98%E3%81%AA%E3%82%B5%E3%83%B3%E3%83%97%E3%83%AB-%E3%82%BF%E3%82%A4%E3%83%A0/)
* [Go Playgroundでランダムを試す](http://u.hinoichi.net/2012/12/25/go-playground%E3%81%A7%E3%83%A9%E3%83%B3%E3%83%80%E3%83%A0%E3%82%92%E8%A9%A6%E3%81%99/)
* [golang and FastCGI](http://u.hinoichi.net/2012/07/11/golang-and-fastcgi/)
* [goweb-msgpack](http://u.hinoichi.net/2012/08/06/goweb-msgpack/)
* [GAE/Gで単体テスト](http://u.hinoichi.net/2012/08/17/gaeg%E3%81%A7%E5%8D%98%E4%BD%93%E3%83%86%E3%82%B9%E3%83%88/)
* [Go言語のコードカバレッジツール](http://u.hinoichi.net/2012/09/06/go%E8%A8%80%E8%AA%9E%E3%81%AE%E3%82%B3%E3%83%BC%E3%83%89%E3%82%AB%E3%83%90%E3%83%AC%E3%83%83%E3%82%B8%E3%83%84%E3%83%BC%E3%83%AB/)
* [Go言語でWebアプリを作るときに便利なライブラリツール](http://u.hinoichi.net/2012/09/11/go%E8%A8%80%E8%AA%9E%E3%81%A7web%E3%82%A2%E3%83%97%E3%83%AA%E3%82%92%E4%BD%9C%E3%82%8B%E3%81%A8%E3%81%8D%E3%81%AB%E4%BE%BF%E5%88%A9%E3%81%AA%E3%83%A9%E3%82%A4%E3%83%96%E3%83%A9%E3%83%AA/)
* [Gowebでクロスドメインリクエスト](http://u.hinoichi.net/2012/09/24/goweb%E3%81%A7%E3%82%AF%E3%83%AD%E3%82%B9%E3%83%89%E3%83%A1%E3%82%A4%E3%83%B3%E3%83%AA%E3%82%AF%E3%82%A8%E3%82%B9%E3%83%88/)
* [Go言語のhttpサーバ上で外部ファイルとしてJavascriptとかCSSを使う](http://u.hinoichi.net/2012/05/21/go%E8%A8%80%E8%AA%9E%E3%81%AEhttp%E3%82%B5%E3%83%BC%E3%83%90%E4%B8%8A%E3%81%A7%E5%A4%96%E9%83%A8%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%A8%E3%81%97%E3%81%A6javascript%E3%81%A8%E3%81%8Bcss%E3%82%92/)
* [Go言語のテンプレートエンジンでHTMLのコメントを出す](http://u.hinoichi.net/2012/05/07/go%E8%A8%80%E8%AA%9E%E3%81%AE%E3%83%86%E3%83%B3%E3%83%97%E3%83%AC%E3%83%BC%E3%83%88%E3%82%A8%E3%83%B3%E3%82%B8%E3%83%B3%E3%81%A7html%E3%81%AE%E3%82%B3%E3%83%A1%E3%83%B3%E3%83%88%E3%82%92%E5%87%BA/)
* [Channel API for Golang](http://u.hinoichi.net/2012/02/23/channel-api-for-golang/)
* [Go言語で jQuery ライクな操作が出来る goquery を試した。](http://mattn.kaoriya.net/software/lang/go/20120914184828.htm)
* [Go言語向けの ORM、gorp がなかなか良い](http://mattn.kaoriya.net/software/lang/go/20120914222828.htm)
* [GAE/GでGoogle Cloud Storageを利用するには](http://takashi-yokoyama.blogspot.jp/2012/08/gaeggoogle-cloud-storage.html)
* [Go言語のWebフレームワーク"goweb"をGAE/Gで動かす](http://takashi-yokoyama.blogspot.jp/2012/07/gowebgowebgaeg.html)
* [Ubuntu 12.04にgolangを”ソースから”インストールする。](http://takashi-yokoyama.blogspot.jp/2012/07/ubuntu-1204golang.html)
* [GAE/Gで時間のチェックDatastore編](http://takashi-yokoyama.blogspot.jp/2012/06/gaegdatastore.html)

148
Books.md Normal file

@ -0,0 +1,148 @@
Sorted by publication date.
# English
* **Go Programming**
* Author: John P. Baugh
* Publication Date: June 16, 2010
* ISBN: 978-1453636671
* **The Way to Go: A Thorough Introduction to the Go Programming Language**
* Author: Ivo Balbaert
* Publication Date: March 8, 2012
* ISBN: 978-1469769165
* **The Go Programming Language Phrasebook**
* Author: David Chisnall
* Publication Date: May 10, 2012
* ISBN: 978-0321817143
* **Programming in Go: Creating Applications for the 21st Century**
* Author: Mark Summerfield
* Publication Date: May 14, 2012
* ISBN: 978-0321774637
* **An Introduction to Programming in Go**
* Author: Caleb Doxsey
* Publication Date: September 3, 2012
* ISBN: 978-1478355823
* References: [site](http://www.golang-book.com/)
* **Learning Go** (e-book)
* Author: Miek Gieben
* Publication Date: ---
* ISBN: ---
* References: [site](http://www.miek.nl/projects/learninggo/)
* **Network Programming with Go** (e-book)
* Author: Jan Newmarch
* Publication Date: ---
* ISBN: ---
* References: [site](http://jan.newmarch.name/go/)
* **Go In Action**
* Authors: Brian Ketelsen, Erik St. Martin, and William Kennedy
* Publication Date: Summer 2015 (est.)
* ISBN: 9781617291784
* References: http://goinactionbook.com
* Discount Code 40% Off: gocenter
# Chinese
* **Go语言·云动力**
* Author: 樊虹剑fango
* Publication Date: 2012-06
* ISBN: 978-7-115-28307-8
* Reference: http://www.ituring.com.cn/book/1040
* **Go语言编程**
* Author: 许式伟
* Publication Date: 2012-08
* ISBN: 978-7-115-29036-6
* Reference: http://www.ituring.com.cn/book/967
* **Go Web编程**
* Author: 谢孟军
* Publication Date: 2013-05
* ISBN: 9787121200915
* Reference: https://github.com/astaxie/build-web-application-with-golang/
* **Go语言程序设计(Programming in Go: Creating Applications for the 21st Century)**
* Author: Mark Summerfield
* Translator: 许式伟, 吕桂华, 徐立, 何李石
* Publication Date: 2013-08
* ISBN: 978-7-115-31790-2
* Reference: http://www.ptpress.com.cn/Book.aspx?id=35714
* **Go语言程序设计(21世纪高等学校规划教材·计算机科学与技术)**
* Author: 王鹏
* Publication Date: 2013-12-18
* ISBN: 9787302347231
* Reference: http://www.tup.com.cn/sub_press/4/book/Showbook.asp?CPBH=054436-01
* **学习 Go 语言** (e-book / Translation)
* Author: Xing Xing (mikespook)
* Publication Date: ---
* ISBN: ---
* References: [site](http://www.mikespook.com/learning-go/)
# Japanese
* **はじめての「Go言語」**
* Author: 茨木 隆彰
* Publication Date: 2010-11
* ISBN: 978-4777515592
* Reference:
* **Go言語プログラミング入門on Google App Engine**
* Author: 横山 隆司
* Publication Date: 2011-12
* ISBN: 978-4798031804
* Reference:
* **はじめてのGoogle App Engine Go言語編**
* Author: 茨木 隆彰
* Publication Date: 2012-2
* ISBN: 978-4777516605
* Reference:
* **プログラミング言語Goフレーズブック**
* Author: David Chisnall (著), デイビッド・チズナール (著), 柴田 芳樹 (翻訳)
* Publication Date: 2012-10
* ISBN: 978-4864010962
* Reference:
* **基礎からわかる Go言語**
* Author: 古川 昇
* Publication Date: 2012-11
* ISBN: 978-4863541177
* Reference:
# German
* **Programmierung in Google Go** (e-book)
* Authors: Rainer Feike and Steffen Blass
* ISBN: 978-3-8632-4722-5
* Publication Date: 2010-11
* Reference: http://bookshop.pearson.de/main/main.asp?page=bookdetails&productid=181679
* **Systemprogrammierung in Google Go**
* Author: Frank Müller
* Publication Date: 2011-01
* ISBN: 978-3-89864-712-0
* Reference: http://dpunkt.de/buecher/3449/systemprogrammierung-in-google-go.html
* **Nichtsequentielle Programmierung mit Go 1** (2nd edition) (available as print and e-book)
* Author: Christian Maurer
* Publication Date: 2012
* ISBN: 978-3-642-29968-1
* Reference: http://www.springer.com/computer/swe/book/978-3-642-29968-1
* **Einstieg in Google Go** (e-book)
* Author: Christian Himpel and Mario Deilmann
* Publication Date: 2012-04
* ISBN: 978-3-86802-415-9
* Reference: http://entwickler.de/press/Einstieg-in-Google-Go
# Brazilian Portuguese
* **Programando em Go: crie aplicações com a linguagem do Google**
* Author: Caio Filipini
* Publication Date: 2014-07-01
* ISBN: 978-85-66250-49-7
* Reference: http://www.casadocodigo.com.br/products/livro-google-go

28
BoundingResourceUse.md Normal file

@ -0,0 +1,28 @@
# Bounding resource use
To bound a program's use of a limited resource, like memory, have goroutines synchronize their use of that resource using a buffered channel (i.e., use the channel as a semaphore):
```
const (
AvailableMemory = 10 << 20 // 10 MB
AverageMemoryPerRequest = 10 << 10 // 10 KB
MaxOutstanding = AvailableMemory / AverageMemoryPerRequest
)
var sem = make(chan int, MaxOutstanding)
func Serve(queue chan *Request) {
for {
sem <- 1 // Block until there's capacity to process a request.
req := <-queue
go handle(req) // Don't wait for handle to finish.
}
}
func handle(r *Request) {
process(r) // May take a long time & use a lot of memory or CPU
<-sem // Done; enable next request to run.
}
```
## References
Effective Go's discussion of channels: http://golang.org/doc/effective_go.html#channels

34
ChromeOS.md Normal file

@ -0,0 +1,34 @@
# Introduction
This tutorial will show you how to install/build/run go on chrome OS. I have tested this using a chrome book Pixel however i do not have any other types of chrome books. However this should work as long as you install the corresponding Linux package for your processor.
# Requirements
Your chrome book must be in developer mode for this to work. Also please note this has only been tested on a 64gb LTE Pixel however it should work on other chrome books
# Install Go
First download the latest version of Go for Linux-amd64 from the [Go Downloads page](https://code.google.com/p/go/downloads/list) after that open a shell by hitting (Crtl+alt+t) and typing in "shell" then hit enter. Then extract it using the following command.```
sudo tar -C /usr/local -xzf ~/Downloads/FILENAMEHERE``` Go should now be installed you can test this by typing "/usr/local/go/bin/go" if it installed you should see the go help prompt. Congrats Go is now installed however you will not be able to run anything because chrome mounts partitions with noexec. The following will guide you through remounting your home folder, and setting up paths that are persistent across reboots, and shell sessions.
# Create a Workspace
To keep this simple just create a folder called "gocode" in your downloads folder. Also create a folder called "src" inside.
# Set Paths & Exec
Either type the following into your shell each session or if you want it to be persistent between sessions add it to your "~/.bashrc" file. The last line remounts your user folder so that you can run your go code other wise you would get permission errors.
```
export PATH=$PATH:/usr/local/go/bin
export GOPATH=~/Downloads/gocode
export PATH=$PATH:$GOPATH/bin
sudo mount -i -o remount,exec /home/chronos/user/
```
This will allow you to run your go object files in your shell.
# Test If It Worked
First add a "hello" folder inside of your "gocode/src" folder. After that create a file in your "gocode/src/hello" folder called "hello.go" with the following in it. Then run "go install hello" then "hello" and you should see "Hello, chrome os" in the console.
```
package main
import "fmt"
func main() {
fmt.Printf("Hello, chrome os\n")
}```

104
CodeReview.md Normal file

@ -0,0 +1,104 @@
Be sure to familiarize yourself with the [code review process](http://golang.org/doc/contribute.html#Code_review) from the official Contribution Guidelines first.
# Reviewer Parlance
There are several terms code reviews may use that you should become familiar with.
* ` LGTM ` — looks good to me: the reviewer approves of your changes as they currently are. The reviewer may suggest minor changes; if so, you can make those changes, and then submit.
* ` NOT LGTM ` — does not look good to me: the reviewer disapproves of your changes entirely. The reviewer will explain why they disapprove of your changes.
* ` SGTM ` — sounds good to me: the reviewer approves of an idea mentioned in the review, but does not approve the changes for commit at this point.
* ` s/foo/bar/ ` — The reviewer has requested that you replace the text ` foo ` with ` bar ` where they have commented. This notation originates from [sed syntax](http://en.wikipedia.org/wiki/Sed#Usage).
* ` s/foo/bar/g ` — The reviewer has requested that you replace the text ` foo ` with ` bar ` throughout your entire change. This notation originates from [sed syntax](http://en.wikipedia.org/wiki/Sed#Usage).
* ` CC=person ` — The reviewer has requested that ` person ` receive a copy of this review. This often originates from the [Go development dashboard](http://go-dev.appspot.com/).
* ` R=person ` — The reviewer has requested for ` person ` to review this code before it is committed. This often originates from the [Go development dashboard](http://go-dev.appspot.com/).
* ` R=close ` — The reviewer has requested that you close the review for now. They will explain why they wish for you to close the review.
* ` TBR=person ` — This does not appear in code reviews themselves, but may appear in commit messages. In this case, the committer has requested that ` person ` review this code as soon as possible, but the change is considered acceptable to be committed immediately.
# Email
Messages from a code review are typically sent to three places:
* the review itself
* the golang-codereviews group
* email
If you are replying to a review comment through email or the golang-codereviews group, you will notice two extra email addresses - golang-codereviews@googlegroups.com and reply@codereview-hr.appspotmail.com. The former address ensures your message is posted to the golang-codereviews group, and the latter ensures your message is posted back to the review itself. Keeping both of these on your replies makes sure your review message is visible everywhere.
# Code Review on Windows
The code review extension depends on Python modules that are not currently included in the standalone Mercurial installer for Windows. Attempting to use the code review extension will result in a "` *** failed to import extension codereview `" error.
## Option 1: Source Installation
To ensure that your Mercurial installation is compatible with the code review plugin, the "source install" package should be used instead of the standalone installer. The process to do this is as follows:
* Check the Mercurial download page to determine the required Python version.
* Install Python using the Windows installer from the Python download page.
* Install Mercurial using the "Mercurial X.XX for Python X.X on Windows (source install)" installer from the Mercurial download page.
* Update your ` PATH ` to include the Python installation directory and its ` scripts ` subdirectory.
## Option 2: Standalone Installation
If you would rather use the standalone Mercurial installer, it is possible to add the missing modules after completing the installation. You will need to copy files from the ` lib ` directory of an existing Python installation to the root directory of the ` library.zip ` file in the Mercurial installation directory. Depending on the version of Mercurial you have installed, the following files/directories may be needed:
* the ` json/ ` subdirectory
* ` htmlentitydefs.py `
* ` HTMLParser.py `
* ` markupbase.py `
# Dealing with Conflicts
When I run ` hg clpatch NNNN `, I get "patch and recent changes conflict". What do I do?
## Option 1: clpatch the old revision, use hg to merge
```
hg clp NNNN
# look at the revision that CL is against; call that revision AAAA
hg up AAAA
hg clp --no_incoming NNNN
hg up
# fix the merge conflicts, if any
# optionally, upload the merged revision:
hg upl NNNN
```
## Option 2: Apply the diff from the codereview website
Visit ` https://codereview.appspot.com/NNNN/ ` and note the raw diff url. It'll likely be something like ` https://codereview.appspot.com/download/issueNNNN_X0001.diff `.
```
# clpatch to bring in the CL metadata
hg clpatch --ignore_hgapplydiff_failure NNNN
# apply the diff
hg import --no-commit --force DIFF_URL
# fix the tree
# optionally, upload the merged revision:
hg upl NNNN
```
# Reverting local changes
You've run ` hg clpatch NNNN `, and you want to restore your repo to a clean state.
```
# Revert file changes.
hg revert @NNNN
# Remove local CL metadata.
hg change -D NNNN
# Remove added files. DANGER: Will delete *all* untracked files.
hg purge
```
# Submitting
If you were just given submit access, congrats. Some tips:
* To check that you do in fact have submit access, go to any issue and click to enter a comment. If you have submit access, you'll notice a lot of extra options available beyond just commenting.
* To submit, you'll need to configure mercurial to authorize with code.google.com. You can do this via the ` .hgrc ` auth section. Sample:
```
[auth]
go.prefix = https://code.google.com/p/go
go.username = *****@****.com
go.password = **********
```
* By default, the password used for code.google.com is **not** your regular Google account password; visit https://code.google.com/hosting/settings.

255
CodeReviewComments.md Normal file

@ -0,0 +1,255 @@
(TODO: Add table of contents.)
# Go Code Review Comments
This page collects common comments made during reviews of Go code, so
that a single detailed explanation can be referred to by shorthands.
This is a laundry list of common mistakes, not a style guide.
You can view this as a supplement to http://golang.org/doc/effective_go.html.
**Please discuss changes before editing this page**, even _minor_ ones. Many people have opinions and this is not the place for edit wars.
## gofmt
Run [gofmt](http://golang.org/cmd/gofmt/) on your code to automatically fix the majority of mechanical style issues. Almost all Go code in the wild uses ` gofmt `. The rest of this document addresses non-mechanical style points.
An alternative is to use [goimports](https://godoc.org/code.google.com/p/go.tools/cmd/goimports), a superset of ` gofmt ` which additionally adds (and removes) import lines as necessary.
## Comment Sentences
See http://golang.org/doc/effective_go.html#commentary. Comments documenting declarations should be full sentences, even if that seems a little redundant. This approach makes them format well when extracted into godoc documentation. Comments should begin with the name of the thing being described and end in a period:
```
// A Request represents a request to run a command.
type Request struct { ...
// Encode writes the JSON encoding of req to w.
func Encode(w io.Writer, req *Request) { ...
```
and so on.
## Doc Comments
All top-level, exported names should have doc comments, as should non-trivial unexported type or function declarations. See http://golang.org/doc/effective_go.html#commentary for more information about commentary conventions.
## Don't Panic
See http://golang.org/doc/effective_go.html#errors. Don't use panic for normal error handling. Use error and multiple return values.
## Error Strings
Error strings should not be capitalized (unless beginning with proper nouns or acronyms) or end with punctuation, since they are usually printed following other context. That is, use fmt.Errorf("something bad") not fmt.Errorf("Something bad"), so that log.Print("Reading %s: %v", filename, err) formats without a spurious capital letter mid-message. This does not apply to logging, which is implicitly line-oriented and not combined inside other messages.
## Handle Errors
See http://golang.org/doc/effective_go.html#errors. Do not discard errors using ` _ ` variables. If a function returns an error, check it to make sure the function succeeded. Handle the error, return it, or, in truly exceptional situations, panic.
## Imports
Imports are organized in groups, with blank lines between them. The standard library packages are in the first group.
```
package main
import (
"fmt"
"hash/adler32"
"os"
"appengine/user"
"appengine/foo"
"code.google.com/p/x/y"
"github.com/foo/bar"
)
```
<a href='https://godoc.org/code.google.com/p/go.tools/cmd/goimports'>goimports</a> will do this for you.
## Import Dot
The import . form can be useful in tests that, due to circular dependencies, cannot be made part of the package being tested:
```
package foo_test
import (
. "foo"
"bar/testutil" // also imports "foo"
)
```
In this case, the test file cannot be in package foo because it uses bar/testutil, which imports foo. So we use the 'import .' form to let the file pretend to be part of package foo even though it is not. Except for this one case, do not use import . in your programs. It makes the programs much harder to read because it is unclear whether a name like Quux is a top-level identifier in the current package or in an imported package.
## Indent Error Flow
Try to keep the normal code path at a minimal indentation, and indent the error handling, dealing with it first. This improves the readability of the code by permitting visually scanning the normal path quickly. For instance, don't write
```
if err != nil {
// error handling
} else {
// normal code
}
```
Instead, write
```
if err != nil {
// error handling
return // or continue, etc.
}
// normal code
```
If the if statement has an initialization statement that, such as
```
if x, err := f(); err != nil {
// error handling
return
} else {
// use x
}
```
then this may require moving the short variable declaration to its own line:
```
x, err := f()
if err != nil {
// error handling
return
}
// use x
```
## Initialisms
Words in names that are initialisms or acronyms (e.g. "URL" or "NATO") have a consistent case. For example, "URL" should appear as "URL" or "url" (as in "urlPony", or "URLPony"), never as "Url". Here's an example: ServeHTTP not ServeHttp.
This rule also applies to "ID" when it is short for "identifier," so write "appID" instead of "appId".
Code generated by the protocol buffer compiler is exempt from this rule. Human-written code is held to a higher standard than machine-written code.
## Line Length
There is no rigid line length limit in Go code, but avoid uncomfortably long lines. Similarly, don't add line breaks to keep lines short when they are more readable long--for example, if they are repetitive.
Comments are typically wrapped before no more than 80 characters, not because it's a rule, but because it's more readable when viewing in an editor that might be sized to show hundreds of columns wide. Humans are better at following narrow text (e.g. columns in a newspaper) than giant walls of wide text, as a wide editor might show. Regardless, godoc should render it nicely either way.
## Mixed Caps
See http://golang.org/doc/effective_go.html#mixed-caps. This applies even when it breaks conventions in other languages. For example an unexported constant is ` maxLength ` not ` MaxLength ` or ` MAX_LENGTH `.
## Named Result Parameters
Consider what it will look like in godoc. Named result parameters like:
```
func (n *Node) Parent1() (node *Node)
func (n *Node) Parent2() (node *Node, err error)
```
will stutter in godoc; better to use:
```
func (n *Node) Parent1() *Node
func (n *Node) Parent2() (*Node, error)
```
On the other hand, if a function returns two or three parameters of the same type, or if the meaning of a result isn't clear from context, adding names may be useful. For example:
```go
func (f *Foo) Location() (float64, float64, error)```
is less clear than
```go
// Location returns f's latitude and longitude.
// Negative values mean south and west, respectively.
func (f *Foo) Location() (lat, long float64, err error)```
Naked returns are okay if the function is a handful of lines. Once it's a medium-sized function, be explicit with your return values. Corollary: it's not worth it to name result parameters just because it enables you to use naked returns. Clarity of docs is always more important than saving a line or two in your function.
Finally, in some cases you need to name a result parameter in order to change it in a deferred closure. That is always okay.
## Naked Returns
See [CodeReviewComments#Named\_Result\_Parameters](wiki/CodeReviewComments#Named_Result_Parameters).
## Package Comments
Package comments, like all comments to be presented by godoc, must appear adjacent to the package clause, with no blank line.
```
// Package math provides basic constants and mathematical functions.
package math
```
```
/*
Package template implements data-driven templates for generating textual
output such as HTML.
....
*/
package template
```
See http://golang.org/doc/effective_go.html#commentary for more information about commentary conventions.
## Package Names
All references to names in your package will be done using the package name, so you can omit that name from the identifiers. For example, if you are in package chubby, you don't need type ChubbyFile, which clients will write as chubby.ChubbyFile. Instead, name the type File, which clients will write as chubby.File. See http://golang.org/doc/effective_go.html#package-names for more.
## Pass Values
Don't pass pointers as function arguments just to save a few bytes. If a function refers to its argument ` x ` only as ` *x ` throughout, then the argument shouldn't be a pointer. Common instances of this include passing a pointer to a string (` *string `) or a pointer to an interface value (` *io.Reader `). In both cases the value itself is a fixed size and can be passed directly. This advice does not apply to large structs, or even small structs that might grow.
## Receiver Names
The name of a method's receiver should be a reflection of its identity; often a one or two letter abbreviation of its type suffices (such as "c" or "cl" for "Client"). Don't use generic names such as "me", "this" or "self", identifiers typical of object-oriented languages that place more emphasis on methods as opposed to functions. The name need not be as descriptive as a that of a method argument, as its role is obvious and serves no documentary purpose. It can be very short as it will appear on almost every line of every method of the type; familiarity admits brevity. Be consistent, too: if you call the receiver "c" in one method, don't call it "cl" in another.
## Receiver Type
Choosing whether to use a value or pointer receiver on methods can be difficult, especially to new Go programmers. If in doubt, use a pointer, but there are times when a value receiver makes sense, usually for reasons of efficiency, such as for small unchanging structs or values of basic type. Some rules of thumb:
* If the receiver is a map, func or chan, don't use a pointer to it.
* If the receiver is a slice and the method doesn't reslice or reallocate the slice, don't use a pointer to it.
* If the method needs to mutate the receiver, the receiver must be a pointer.
* If the receiver is a struct that contains a sync.Mutex or similar synchronizing field, the receiver must be a pointer to avoid copying.
* If the receiver is a large struct or array, a pointer receiver is more efficient. How large is large? Assume it's equivalent to passing all its elements as arguments to the method. If that feels too large, it's also too large for the receiver.
* Can function or methods, either concurrently or when called from this method, be mutating the receiver? A value type creates a copy of the receiver when the method is invoked, so outside updates will not be applied to this receiver. If changes must be visible in the original receiver, the receiver must be a pointer.
* If the receiver is a struct, array or slice and any of its elements is a pointer to something that might be mutating, prefer a pointer receiver, as it will make the intention more clear to the reader.
* If the receiver is a small array or struct that is naturally a value type (for instance, something like the time.Time type), with no mutable fields and no pointers, or is just a simple basic type such as int or string, a value receiver makes sense. A value receiver can reduce the amount of garbage that can be generated; if a value is passed to a value method, an on-stack copy can be used instead of allocating on the heap. (The compiler tries to be smart about avoiding this allocation, but it can't always succeed.) Don't choose a value receiver type for this reason without profiling first.
* Finally, when in doubt, use a pointer receiver.
## Useful Test Failures
Tests should fail with helpful messages saying what was wrong, with what inputs, what was actually got, and what was expected. It may be tempting to write a bunch of assertFoo helpers, but be sure your helpers produce useful error messages. Assume that the person debugging your failing test is not you, and is not your team. A typical Go test fails like:
```
if got != tt.want {
t.Errorf("Foo(%q) = %d; want %d", tt.in, got, tt.want) // or Fatalf, if test can't test anything more past this point
}
```
Note that the order here is actual != expected, and the message uses that order too. Some test frameworks encourage writing these backwards: 0 != x, "expected 0, got x", and so on. Go does not.
If that seems like a lot of typing, you may want to write a table-driven test: http://code.google.com/p/go-wiki/wiki/TableDrivenTests
Another common technique to disambiguate failing tests when using a test helper with different input is to wrap each caller with a different TestFoo function, so the test fails with that name:
```
func TestSingleValue(t *testing.T) { testHelper(t, []int{80}) }
func TestNoValues(t *testing.T) { testHelper(t, []int{}) }
```
In any case, the onus is on you to fail with a helpful message to whoever's debugging your code in the future.
## Variable Names
Variable names in Go should be short rather than long. This is especially true for local variables with limited scope. Prefer c to lineCount. Prefer i to sliceIndex.
The basic rule: the further from its declaration that a name is used, the more descriptive the name must be. For a method receiver, one or two letters is sufficient. Common variables such as loop indices and readers can be a single letter (` i `, ` r `). More unusual things and global variables need more descriptive names.

23
Comments.md Normal file

@ -0,0 +1,23 @@
# Comments
Every package should have a package comment. It should immediately precede the ` package ` statement in one of the files in the package. (It only needs to appear in one file.) It should begin with a single sentence that begins "Package _packagename_" and give a concise summary of the package functionality. This introductory sentence will be used in godoc's list of all packages.
Subsequent sentences and/or paragraphs can give more details. Sentences should be properly punctuated.
```
// Package superman implements methods for saving the world.
//
// Experience has shown that a small number of procedures can prove
// helpful when attempting to save the world.
package superman
```
Nearly every top-level type, const, var and func should have a comment. A comment for bar should be in the form "_bar_ floats on high o'er vales and hills.". The first letter of _bar_ should not be capitalized unless it's capitalized in the code.
```
// enterOrbit causes Superman to fly into low Earth orbit, a position
// that presents several possibilities for planet salvation.
func enterOrbit() os.Error {
...
}
```

58
CommonMistakes.md Normal file

@ -0,0 +1,58 @@
(TODO: Add table of contents.)
# Introduction
When new programmers start using Go or when old Go programmers start using a new concept, there are some common mistakes that many of them make. Here is a non-exhaustive list of some frequent mistakes that show up on the mailing lists and in IRC.
# Closures
## Using Closures with Goroutines
When iterating in Go, one might also be tempted to use a closure and goroutine to process data in parallel. For example, if you wanted to process values coming in from a channel in their own goroutines, you might write the following code:
```
for val := range values {
go func() {
fmt.Println(val)
}()
}
```
If you don't immediately see the problem with the above code, take a second to see if you can figure out what is wrong with it before you keep reading.
The ` val ` variable in the above loop is actually a single variable that takes on the value of each slice element. Because the closures are all only bound to that one variable, there is a very good chance that when you run this code you will see the last element printed for every iteration instead of each value in sequence, because the goroutines will probably not begin executing until after the loop.
The proper way to write that loop is:
```
for val := range values {
go func(val interface{}) {
fmt.Println(val)
}(val)
}
```
By adding val as a parameter to the closure, ` val ` is evaluated at each iteration and placed on the stack for the goroutine, so each slice element is available to the goroutine when it is eventually executed.
It is also important to note that variables declared within the body of a loop are not shared between iterations, and thus can be used separately in a closure. The following code uses a common index variable ` i ` to create separate ` val `s, which results in the expected behavior:
```
for i := range valslice {
val := valslice[i]
go func() {
fmt.Println(val)
}()
}
```
Note that without executing this closure as a goroutine, the code runs as expected. The following example prints out the integers between 1 and 10.
```
for i := 1; i <= 10; i++ {
func() {
fmt.Println(i)
}()
}
```
Even though the closures all still close over the same variable (in this case, ` i `), they are executed before the variable changes, resulting in the desired behavior.
http://golang.org/doc/go_faq.html#closures_and_goroutines

5
Contributing.md Normal file

@ -0,0 +1,5 @@
# Permissions
Only members of the go-wiki project may edit these wiki pages (this is to keep the number of spammers down).
To join the project, please mail adg@golang.org and request permission.

44
Courses.md Normal file

@ -0,0 +1,44 @@
# Introduction
Go is a great langage for CS majors. This page presents some university courses that uses Go.
# Language
* University of Helsinki, Department of Computer Science used to have a course named Introduction to Go, taught by K. Bäckman: http://www.cs.helsinki.fi/courses/582336 in Spring 2010.
* University of Sofia "St. Kliment Ohridski", Faculty of Mathematics and Informatics has elective course named "Programming with Go", taught by K. Vladimiroff: http://fmi.golang.bg (bulgarian) and their [[public lectures](https://github.com/fmi/go-lectures)] (also in bulgarian)
* Free University of Berlin (Germany) had a course [Introduction to Go Programming](http://w3.inf.fu-berlin.de/lehre/WS12/go/) in Spring 2013.
# Web
* CS 4830: Science and Engineering of the WWW taught by Ryanne Dolan at University of Missouri: http://4830.ryannedolan.info/
# Concurrency
* Go is being used at the end of a yearlong freshman computer science class at KTH: http://www.nada.kth.se/~snilsson/concurrency/.
* Go, Concurrent and Systems Programming from Rochester Institute of Technology: http://www.cs.rit.edu/~ats/go-2011-2/index.xml
* Free University of Berlin (Germany) had a course on [Concurrent Programming](http://w3.inf.fu-berlin.de/lehre/SS13/alp4/) with Go as a reference language in 2013.
* University of Duisburg-Essen (Germany) had a lecture about Go and CSP within their course on [Concurrent systems modelling](http://www.ti.inf.uni-due.de/teaching/ss2014/mod_ns/) in summer 2014. [[Slides](http://www.ti.inf.uni-due.de/fileadmin/public/teaching/mod_ns/folien/SS2014/google-go-2x2.pdf)]
# Distributed Computing
* Distributed Systems course (15-440) at CMU: http://www.cs.cmu.edu/~dga/15-440/F12/index.html (see also http://da-data.blogspot.se/2013/02/teaching-distributed-systems-in-go.html)
* 6.824 Distributed Systems at MIT is using Go in its labs: http://pdos.csail.mit.edu/6.824/.
* Design of Agent-based Systems at University of Jyväskylä: [TIES433](http://users.jyu.fi/~miselico/teaching/TIES433/2013/)
* CSE 223B, Spring 2014: Distributed Computing and Systems at UC San Diego http://cseweb.ucsd.edu/classes/sp14/cse223B-a/index.html
* Dixie State University teaches Go in an introductory course to programming languages and later on in distributed systems.
* CS 352, Computer Organization and Design, at the University of Wisconsin, Eau Claire: http://cs.uwec.edu/~buipj/teaching/cs.352.f13/lab_01_high_performance_computing.html
* KTH Stockholm uses Go to teach concurrency: http://www.nada.kth.se/~snilsson/concurrency/
* Go was used this fall at the University of Tromsø: INF-2202 Concurrent and System Level Programming http://uit.no/studietilbud/emner/emne?p_document_id=330794
* Norwegian University of Science and Technology: TTK4145 Real-Time Programming http://www.itk.ntnu.no/fag/TTK4145/information/

74
DashboardBuilders.md Normal file

@ -0,0 +1,74 @@
# Introduction
This page lists details of the various builders assigned to the build.golang.org CI system
## New-style Builders
See http://golang.org/s/builderplan
| **title** | **description** | **owner** | **notes** |
|:----------|:----------------|:----------|:----------|
| linux-386 | in Docker on GCE | bradfitz | |
| linux-386-387 | in Docker on GCE | bradfitz | GO386=387 |
| linux-386-clang | in Docker on GCE | bradfitz | Debian wheezy + clang 3.5 instead of gcc |
| linux-386-sid | in Docker on GCE | bradfitz | Debian sid |
| linux-amd64 | in Docker on GCE | bradfitz | |
| linux-amd64-clang | in Docker on GCE | bradfitz | Debian wheezy + clang 3.5 instead of gcc |
| linux-amd64-nocgo | in Docker on GCE | bradfitz | cgo disabled |
| linux-amd64-noopt | in Docker on GCE | bradfitz | optimizations and inlining disabled |
| linux-amd64-race| in Docker on GCE | bradfitz | |
| linux-amd64-sid | in Docker on GCE | bradfitz | Debian sid |
| nacl-386 | in Docker on GCE | bradfitz | |
| nacl-amd64p32 | in Docker on GCE | bradfitz | |
## Legacy Builders
These builders are configured and run manually. The goal is to migrate as many as possible over to the new system.
| **title** | **description** | **owner** | **notes** |
|:----------|:----------------|:----------|:----------|
| darwin-amd64 | 2011 Mac Mini, 2.4Ghz Core i5 | adg | Mac OS X 10.6 (10K549) |
| darwin-amd64-cheney | 2011 Mac Mini, 2.4Ghz Core i5 | Dave Cheney | Mac OS X 10.10 XCode 5 |
| darwin-amd64-race-cheney | 2011 Mac Mini, 2.4Ghz Core i5 | Dave Cheney | Mac OS X 10.10 XCode 5 |
| darwin-386 | 2011 Mac Mini, 2.4Ghz Core i5 | adg | Mac OS X 10.6 (10K549) |
| darwin-386-cheney | 2011 Mac Mini, 2.4Ghz Core i5 | Dave Cheney | Mac OS X 10.10 XCode 5 |
| dragonfly-amd64 | ? | Justin Sherrill | ? |
| dragonfly-386 | ? | Justin Sherrill | ? |
| freebsd-386 | rootbsd.net VPS | adg | FreeBSD 9.1 |
| freebsd-amd64 | rootbsd.net VPS | adg | FreeBSD 9.1 |
| freebsd-amd64-race | rootbsd.net VPS | adg | FreeBSD 9.2, Only runs -race tests (./race.bash) |
| linux-arm-luitvd | RaspberryPi | Luit van Drongelen | |
| linux-arm-arm5 | QNAP TS-119P, ARMv5 @ 2.0GHz, 512MB | Dave Cheney | GOARM=5 |
| linux-arm-cheney-imx6 | Solidrun Cubox-i, quad core Cortex-A9 ~ 1Ghz, 2Gb ram | Dave Cheney | Runs arch linux, iMX6 boards need 3.10.x or above to pass the build reliably |
| nacl-arm | samsung chromebook | rsc | running chrubuntu |
| nacl-arm-cheney | same builder as linux-arm-cheney-imx6 | Dave Cheney | |
| openbsd-386-rootbsd | VM on RootBSD | adg | OpenBSD 5.4-current |
| openbsd-386-crawshaw | VM | crawshaw | OpenBSD 5.5 |
| openbsd-amd64-rootbsd | VM on RootBSD | adg | OpenBSD 5.4-current |
| netbsd-386-minux | KVM | Shenghou Ma | |
| netbsd-amd64-bsiegert | EC2 m1.small VM | Benny Siegert | on Brad's work EC2 account |
| plan9-386-cnielsen | Intel Core 2 Quad Q8200 2.33 GHz, 6GB | David du Colombier | Plan 9 from Bell Labs, updated nightly |
| plan9-amd64-aram | VM | Nick Owens | runs 9front |
| solaris-amd64-smartos | E5-1650 Xeon, 6C/12T | Daniel Malon | runs illumos (smartos zone); dfc, aram have full access |
| solaris-amd64-solaris11 | VM | Dave Cheney | runs Solaris 11 |
| windows-386 | on GCE 16 core instance, same machine as windows-amd64 | bradfitz | |
| windows-amd64 | on GCE 16 core instance, same machine as windows-386 | bradfitz | |
| windows-amd64-race | Windows 8.1, 2 x Intel Xeon E5620 @ 2.4GHz, 8 HT cores, 12GB RAM | Dmitry Vyukov | Only runs -race tests (./race.bash) |
# Builder Requirements
* internet connection (at least be able to access Google and http://build.golang.org)
* preferably with two or more (V)CPUs, as at least one test (` sync/atomic ` requires ` runtime.NumCPU() > 1 ` to test more completely)
* at least 512MiB of memory
# Restrictions
* The combination of Ubuntu 11.10 or 12.04 OMAP4 kernel and pandaboard (ES) have proven unstable as builders. See [issue 4305](https://code.google.com/p/go/issues/detail?id=4305). Make sure you have updated to the latest available 12.04.2 release.
# How to set up a builder
1. obtain a hash from Go team members, and put that in ` ~/.gobuildkey `
1. go get code.google.com/p/go.tools/dashboard/builder
1. builder YOUR\_BUILDER\_NAME
# Special notes
* Please make sure you've installed root certificates and it's accessible to Go programs. For example, on NetBSD, you will need to install ` security/mozilla-rootcerts `.
* If your builder runs Unix, please install ` perl `, as tests for ` go.tools/cmd/vet ` need it.
* Use ` screen(1) ` instead of ` tmux(1) ` to host the ` builder ` process, as the later interference with some of the ` os/signal ` tests.
* Raise ` ulimit `s on Unix: thread count (` -r `), nofiles (` -n `, 1024 should be fine)

52
DesignDocuments.md Normal file

@ -0,0 +1,52 @@
# Go 1.1
* [net/http/cookiejar](https://groups.google.com/d/msg/golang-dev/ygDB3nbir00/rouknDcuyakJ)
* [Function Calls](https://docs.google.com/document/d/1bMwCey-gmqZVTpRax-ESeVuZGmjwbocYs1iHplK-cjo/pub)
# Go 1.2
* [xml.Marshaler and Umarshaler](http://golang.org/s/go12xml)
* [encoding.TextMarshaler and Unmarshaler](http://golang.org/s/go12encoding)
* [Runtime Symbol Table Format](http://golang.org/s/go12symtab)
* [Field Selectors and Nil Checks](http://golang.org/s/go12nil)
* x[i:j:k] [Slice Syntax](http://golang.org/s/go12slice)
* [Preemptive Scheduler](https://docs.google.com/document/d/1ETuA2IOmnaQ4j81AtTGT40Y4_Jr6_IDASEKg0t0dBR8/edit?usp=sharing)
# Go 1.3
* [Contiguous Stacks](https://docs.google.com/document/d/1wAaf1rYoM4S4gtnPh0zOlGzWtrZFQ5suE8qr2sD8uWQ/pub)
* [Go 1.3 Linker Overhaul](https://golang.org/s/go13linker)
* [Go 1.3 Native Client Support](https://docs.google.com/document/d/1oA4rs0pfk5NzUyA0YX6QsUEErNIMXawoscw9t0NHafo/pub)
# Go 1.4
* [Go channels on steroids](http://golang.org/s/go13chan)
* [Go 1.4 “Internal” Packages](http://golang.org/s/go14internal)
* [Go 1.4 src/pkg → src](http://golang.org/s/go14nopkg)
* [Go 1.4 Custom Import Path Checking](http://golang.org/s/go14customimport)
* [Go generate: A Proposal](http://golang.org/s/go1.4-generate)
* [The syscall package](https://docs.google.com/a/golang.org/document/d/1QXzI9I1pOfZPujQzxhyRy6EeHYTQitKKjHfpq0zpxZs)
* [Go 1.4: unsafe.Pointer arithmetic](https://docs.google.com/a/dempsky.org/document/d/1yyCMzE4YPfsXvnZNjhszaYNqavxHhvbY-OWPqdzZK30/pub)
* [Go 1.4 Subrepo Renaming](http://golang.org/s/go14subrepo)
* [Go Compiler Overhaul](https://docs.google.com/document/d/1P3BLR31VA8cvLJLfMibSuTdwTuF7WWLux71CYD0eeD8/edit)
# Future Proposals
* [dev.cc branch plan](http://golang.org/s/dev.cc)
* [Go 1.4+ Garbage Collection (GC) Plan and Roadmap](http://golang.org/s/go14gc)
* [Better GC and Memory Allocator for Go](https://docs.google.com/document/d/1HCPu3WKyCX3ZRYxmIMKTk0Ik1dePxKW1p02k3uhcft4/view) <br> - <a href='https://groups.google.com/d/topic/golang-dev/pwUh0BVFpY0/discussion'>Groups Discussion</a>
<ul><li><a href='https://docs.google.com/document/d/13v_u3UrN2pgUtPnH4y-qfmlXwEEryikFu0SQiwk35SA/pub'>Precise GC Stack Roots</a>
</li><li><a href='http://golang.org/s/go13fsnotify'>Go 1.3 cmd/go and os/fsnotify</a>
</li><li><a href='http://goo.gl/MrYxyA'>Go 1.5 os/fsnotify API</a>
</li><li><a href='https://docs.google.com/document/d/1eHm7KqfKP9_s4vR1zToxq-FBazdUQ9ZYi-YhcEtdfR0/edit'>Simple Multi-Dimensional Slices (Tables)</a>
</li><li><a href='https://docs.google.com/a/golang.org/document/d/1nr-TQHw_er6GOQRsF6T43GGhFDelrAP0NqSS_00RgZQ/edit#'>Go execution modes</a>
</li><li><a href='http://goo.gl/eXjfeS'>Go Execution Tracer</a>
</li><li><a href='https://docs.google.com/document/d/1d3iI2QWURgDIsSR6G2275vMeQ_X7w-qxM2Vp7iGwwuM/pub'>NUMA-aware scheduler for Go</a>
</li><li><a href='https://docs.google.com/document/d/1CJnU6ZKvsp21B0lQwbJlKFt8Zz4EWscaCRy_EwK8ja8'>Go 1.5+ "External" Packages</a></li></ul>
<h1>Other Tools</h1>
<ul><li><a href='https://docs.google.com/document/d/1WmMHBUjQiuy15JfEnT8YBROQmEv-7K6bV-Y_K53oi5Y'>Go Oracle</a>
</li><li><a href='http://golang.org/s/gobind'>Binding Go and Java</a>
</li><li><a href='http://golang.org/s/builderplan'>Go Builder Plan</a></li></ul>
<h1>Rejected Proposals</h1>
<ul><li><a href='https://docs.google.com/a/golang.org/document/d/1UKu_do3FRvfeN5Bb1RxLohV-zBOJWTzX0E8ZU1bkqX0/edit#heading=h.2wzvdd6vdi83'>Read-only Slices</a>, <a href='https://docs.google.com/document/d/1-NzIYu0qnnsshMBpMPmuO21qd8unlimHgKjRD9qwp2A/edit'>Evaluation of read-only slices</a> (<a href='https://groups.google.com/d/msg/golang-dev/Y7j4B2r_eDw/Rkq-OtEsEBAJ'>rejected</a>)

82
Errors.md Normal file

@ -0,0 +1,82 @@
# Errors
Errors are indicated by returning an ` error ` as an additional return value from a function. A ` nil ` value means that there was no error.
` error `s can be turned into strings by calling ` Error `, their only method. You can create an error from a string by calling ` errors.New `:
```
if failure {
return errors.New("inverse tachyon pulse failed")
}
```
Error strings should not start with a capital letter because they'll often be prefixed before printing:
```
err := TryInverseTachyonPulse()
if err != nil {
fmt.Printf("failed to solve problem: %s\n", err)
}
```
If you expect calling code to be able to handle an error, you can distinguish classes of errors either by returning special values, or new types. You only need to distinguish differences that the calling code could be expected to handle in this way as the string allows one to communicate the details of the error.
` io.EOF ` is a special value that signals the end of a stream. You can compare error values directly against io.EOF.
If you want to carry extra data with the error, you can use a new type:
```
type ParseError struct {
Line, Col int
}
func (p ParseError) Error() string {
return fmt.Sprintf("parse error on line %d, column %d", p.Line, p.Col)
}
```
Calling code would test for a special type of ` error ` by using a type switch:
```
switch err := err.(type) {
case ParseError:
PrintParseError(err)
}
```
## Naming
Error types end in ` "Error" ` and error variables start with ` "Err" `:
```
package somepkg
// ParseError is type of error returned when there's a parsing problem.
type ParseError struct {
Line, Col int
}
var ErrBadAction = errors.New("somepkg: a bad action was performed")
// -----
package foo
func foo() {
res, err := somepkgAction()
if err != nil {
if err == somepkg.ErrBadAction {
}
if pe, ok := err.(*somepkg.ParseError); ok {
line, col := pe.Line, pe.Col
// ....
}
}
}
```
## References
* Errors (specification): http://golang.org/ref/spec#Errors
* Package ` errors `: http://golang.org/pkg/errors/
* Type switches: http://golang.org/doc/go_spec.html#TypeSwitchStmt

16
FreeBSD.md Normal file

@ -0,0 +1,16 @@
# Go on FreeBSD
Required:
* FreeBSD amd64, 386: 8.0 or above
* FreeBSD arm: 10.0 or above
* See http://golang.org/issue/7849 for further information.
| **Kernel version** | **Min. version** | **Max. version**|
|:-------------------|:-----------------|:|
| 11-CURRENT | go1.3 w/ issue 7849 (on Google Code) | go1.4 w/ issue 7849 (on Google Code) |
| 10-STABLE | go1.3 | go1.4 |
| 9-STABLE | go1 | go1.4 |
| 8-STABLE | go1 | go1.4 |
| 7-STABLE | go1 | go1.1 |

52
GOPATH.md Normal file

@ -0,0 +1,52 @@
# Introduction
The GOPATH environment variable is used to specify directories outside of $GOROOT that contain the source for Go projects and their binaries.
See the [go command](http://golang.org/cmd/go/#hdr-GOPATH_environment_variable) and [go/build package](http://golang.org/pkg/go/build/) documentation for more details.
Since the $GOPATH variable can be a list, the rest of this document will use $GOPATH to mean the first element unless otherwise specified.
## Integrating GOPATH
On OS X or Linux, adding the following expression to PATH will add all $GOPATH/bin directories.
```
${GOPATH//://bin:}/bin
```
## Directory layout
The source for a package with the import path ` "X/Y/Z" ` is in the directory
```
$GOPATH/src/X/Y/Z
```
The binary for a package with the import path ` "X/Y/Z" ` is in
```
$GOPATH/pkg/$GOOS_$GOARCH/X/Y/Z.a
```
The binary for a command whose source is in ` $GOPATH/src/A/B ` is
```
$GOPATH/bin/B
```
## Repository Integration and Creating "go gettable" Projects
When fetching a package the go tool looks at the package's import path to discover a URL. For instance, if you attempt to
```
go get code.google.com/p/gomatrix/matrix
```
the go tool will get the source from the project hosted at http://code.google.com/p/gomatrix/. It will clone the repository to
```
$GOPATH/src/code.google.com/p/gomatrix
```
As a result, if (from your repository project) you import a package that is in the same repository, you need to use its "full" import path - the place "go get" puts it. In this example, if something else wants to import the "matrix" package, it should import "code.google.com/p/gomatrix/matrix" rather than "matrix".
## Tips and tricks
### Third-party Packages
It is useful to have two GOPATH entries. One for a location for 3rd party goinstalled packages, and the second for your own projects. List the 3rd party GOPATH first, so that goinstall will use it as a default destination. Then you can work in the second GOPATH directory and have all your packages be importable by using the "go" command, goinstall, or a GOPATH-aware 3rd party build tool like [gb](http://code.google.com/p/go-gb).
## FAQ
### Why won't ` $GOPATH/src/cmd/mycmd/*.go ` build?
When the go command is looking for packages, it always looks in ` $GOROOT ` first. This includes directories, so if it finds (as in the case above) a ` cmd/ ` directory in ` $GOROOT ` it won't proceed to look in any of the GOPATH directories. This prevents you from defining your own ` math/matrix ` package as well as your own ` cmd/mycmd ` commands.

96
GcToolchainTricks.md Normal file

@ -0,0 +1,96 @@
_**Update: the Plan 9 C compilers are going away in future releases of Go (probably in Go 1.5), so some of the tricks below that use them are deprecated.**_
# Introduction
This page documents some less well-known (perhaps advanced) tricks for the ` gc ` toolchain (and the Go tool).
# C code without ` cgo `
### Use the bundled Plan 9 C Compiler ` 6c `
Dave Cheney has written an excellent blog post about this: http://dave.cheney.net/2013/09/07/how-to-include-c-code-in-your-go-package
### Use ` syso ` file to embed arbitrary self-contained C code
Basically, you write your assembly language in GNU as(1) format, but make sure
all the interface functions are using Go's ABI (everything on stack, etc., please read [Go 1.2 Assembler Introduction](http://golang.org/doc/asm) for more details).
The most important step is compiling that file to file.syso (` gcc -c -O3 -o file.syso file.S `),
and put the resulting syso in the package source directory.
And then, suppose your assembly function is named Func, you need one stub
Plan 9 assembly file to call it:
```
TEXT ·Func(SB),$0-8 // please set the correct parameter size (8) here
JMP Func(SB)
```
then you just declare Func in your package and use it, go build will be able to
pick up the syso and link it into the package.
Notes:
* The binary produced won't use cgo, and the overhead is just an unconditional JMP that could be perfectly branch predicted. But, please be aware that because it doesn't use cgo, your assembly function is running on Go stack, and it **shouldn't use too much stack** (a safe value is less than ~100 bytes) or terrible things will happen. For compute kernels, this requirement isn't too restricting.
* Please make sure youve included all library dependencies in your C code. ` libc ` is not available, and most notably, ` libgcc ` is also not available (esp. when you're using gcc ` __builtin_funcs `, please use ` nm(1) ` to double-check that your file doesn't contain any undefined symbols).
* It's also possible to call back Go functions from C code, but this is left as an exercise for the reader.
* this trick is supported on all Go 1.x releases.
* the Go linker is pretty capable in that you just need to prepare .syso file for each architecture, not for each OS/Arch combination (assuming you don't use OS-specific constructs, obviously), and the Go linker is perfectly capable to link, for example, Mach-O object files into ELF binaries. So be sure to name your syso file with names like ` file_amd64.syso `, ` file_386.syso `.
# Bundle data into Go binary
There are a lot of ways to bundle data in Go binary, for example:
* ` zip ` the data files, and append the zip file to end of Go binary, then use ` zip -A prog ` to adjust the bundled zip header. You can use ` archive/zip ` to open the program as a zip file, and access its contents easily. There are existing packages that helps with this, for example, https://godoc.org/bitbucket.org/tebeka/nrsc; This requires post-processing the program binary, which is not suitable for non-main packages that require static data. Also, you must collect all data files into one zip file, which means that it's impossible to use multiple packages that utilize this method.
* Embed the binary file as a ` string ` or ` []byte ` in Go program. This method is not recommended, not only because the generated Go source file is much larger than the binary files themselves, also because static large ` []byte ` slows down the compilation of the package and the ` gc ` compiler uses a lot of memory to compile it (this is a known bug of ` gc `). For example, see the [go.tools/godoc/static](http://godoc.org/code.google.com/p/go.tools/godoc/static) package.
* use similar ` syso ` technique to bundle the data. Precompile the data file as syso file using GNU ` as(1) `'s ` .incbin ` pseudo-instruction.
The key trick for the 3rd alternative is that the linker for the ` gc ` toolchain has the ability to link COFF object files of a different architecture into the binary without problem, so you don't need to provide syso files for all supported architectures. As long as the syso file doesn't contain instructions, you can just use one to embed the data.
The assembly template to generate the COFF .syso file:
```
/* data.S, as -o data.syso */
.section .rdata,"dr" /* put in COFF section .rdata */
.globl _bindataA /* no longer need to prepend package name here */
.globl _ebindataA
_bindataA:
.incbin "dataA"
_ebindataA:
.globl _bindataB /* no longer need to prepend package name here */
.globl _ebindataB
_bindataB:
.incbin "dataB"
_ebindataB:
```
And two other files, first a Plan 9 C source file that assembles the slice for Go:
```
/* slice.c */
#include "runtime.h"
extern byte _bindataA[], _bindataB[], _ebindataA, _ebindataB;
void ·getDataSlices(Slice a, Slice b) {
a.array = _bindataA;
a.len = a.cap = &_ebindataA - _bindataA;
b.array = _bindataB;
b.len = b.cap = &_ebindataB - _bindataB;
FLUSH(&a);
FLUSH(&b);
}
```
And finally, the Go file that uses the embedded slide:
```
/* data.go */
package bindata
func getDataSlices() ([]byte, []byte) // defined in slice.c
var A, B = getDataSlices()
```
Note: you will need an ` as(1) ` capable of generating the COFF syso file, you
can build one easily on Unix:
```
wget http://ftp.gnu.org/gnu/binutils/binutils-2.22.tar.bz2 # any newer version also works
tar xf binutils-2.22.tar.bz2
cd binutils-2.22
mkdir build; cd build
../configure --target=i386-foo-pe --enable-ld=no --enable-gold=no
make
# use gas/as-new to assemble your data.S
# all the other file could be discarded.
```
**Drawback** of this issue is that it seems incompatible to cgo, so only use it when you don't
use cgo, at least for now. I (minux) is working on figuring out why they're incompatible.

113
GccgoCrossCompilation.md Normal file

@ -0,0 +1,113 @@
# Introduction
If you want to run your Go programs on a platform that is not supported by the standard Go compiler _gc_ you can build a version of the GCC compiler that targets your desired target platform, since GCC supports many more platforms. This is possible because there is a Go frontend to GCC named [gccgo](https://code.google.com/p/gofrontend/).
# Details
## Definitions
* **Build** This is the computer where you are building the cross-compiler.
* **Host** The computer that will run the cross-compiler once it's built. This is usually the same as Build.
* **Target** This is the destination system, where you want the cross-compiled program to run.
More definitions and complex cross situations can be found at the [Wikipedia article](http://en.wikipedia.org/wiki/Cross_compiler).
## Go tools and gccgo
You will later need to source code to the Go tool, so you might as well uninstall the version you have installed from your package manager to avoid confusion (fully optional tho). Also build & install gccgo targeting host(!, that's right, you need a gcco compiling for not only target but one for host).
* [Installing Go from source](http://golang.org/doc/install/source)
* [Official Go documentation](http://golang.org/doc/install/gccgo)
## Build the cross-compiler
### Build
First you have to build your cross-compiling version of GCC. This is complex process as it requires several stages with bootstrapping since there are mutual dependency relations between GCC and libc implementations. A very fine tutorial on how to build a GCC cross-toolchain with eglic (works with glibc too) was written by Jim Blandy and posted at eglibc's mailinglist [patches Cross-building instructions](http://www.eglibc.org/archives/patches/msg00078.html). In the final stage where the full GCC is built, simply configure script with _--enable-languages=c,c++,go_ (see [official Go documentation](http://golang.org/doc/install/gccgo)).
You can use the [ewxb\_gcc\_cross-compiler\_builder](https://github.com/erikw/ewxb_gcc_cross-compiler_builder) script as a starting point. Don't expect that script to work out of the box, but rather as a hint to which steps you're likely to take when building your x-toolchain.
If you're lucky enough and want a version of GCC that is not bleeding edge (which you might want to have the latest Go features) you can use a cross-compiler builder to ease the configuration e.g. [crosstool-NG](http://crosstool-ng.org/) that lets you configure GCC with a simple TUI menu. You might have to manually patch the source of _crosstool-NG_ and add go to the languages to include. In crosstool-ng-` <ver> `/scripts/build/cc/gcc.sh modify like this:
```
- --enable-languages="${lang_list}"
+ --enable-languages="go,${lang_list}"
```
### Symlink
You should now have a bin directory with files with names like "` <target `>-gcc", "` <target `>-gnu-gccgo" etc. Because the go build tool does not allow you to specify file-names of the compilers to use (only statically supports the strings 'gc' and 'gccgo') it will look in your $PATH envvar for the first file named 'gccgo' and 'gcc'. You will therefore have to add this directory as an overlay by setting it to be the first one in $PATH when you want to use the cross-compiler and not your normal gcc binary on your system. Since the go tool looks for a binary named _gccgo_ you'll have to make some symlinks for the tools you want it to find.
```
$ cd path/to/cross-comp-gcc/bin
$ ln -s <arch>-<os>-gnu-gcc gcc
$ ln -s <arch>-<os>-gnu-gccgo gccgo
$ ln -s <arch>-<os>-gnu-ar ar
$ export PATH="path/to/crosscomp-gcc/bin:$PATH" # Do this whenever you want to use the cross-compilers targeting your target instead of the system default targeting host.
```
etc.
With $TARGET set to the target architecture and $PREFIX set to the destination path of the built files, you can make the symlinks with:
```
#!/usr/bin/env bash
cd $PREFIX/bin
for file in $(find . -type f); do
tool_name=$(echo $file | sed -e "s/${TARGET}-\(.*\)$/\1/")
ln -sf "$file" "$tool_name"
done
```
### Test
When the cross-compiler is build you should test that it works, both for a simple C program and a simple Go program.
```
$ gccgo -Wall -o helloworld helloworld.go
$ file helloworld # verify that the architecture of the binary is the desired target and not a binary that can run on your host machine.
$ <upload-command-to-target> helloworld
$ <ssh/telnet etc. to target and test run>
```
### Gotchas
If you haven't compiled a shared object of the go library, _libgo_, for your target you might want to compile your Go programs statically, just like _gc_ does, to include all what is needed to run your program. Do this by adding the _-static_ switch to gccgo. If you're unsure how your produced ELF file is liked, inspect it with _readelf -d ` <elf `>_ or _objdump -T ` <elf `>_.
## Build a cross-gccgo aware version of the Go tool
### Assumptions
* Assuming that you've followed the instructions on [Installing Go from source](http://golang.org/doc/install/source) you should have a checked out version of the go source at _$GOROOT_.
* Envvar _$GOROOT_ is set.
* The envvars _$GOARCH_ and _$GOOS_ represent the **target** architecture and operating system. Figure these out and set them to these values when you want to cross-compile.
### Build
You can specify the compiler to use when building with the go tool with _go build -compiler gccgo ` <go-package,files> `_. This is however not enough. If you have set _$GOARCH_ and _$GOOS_ to something that is not supported by _gc_ but with _gccgo_ you have to build a special version of the go tool that understands these extra architectures. If you compile another version of the go tool with the go tool but specify to use gccgo targeting your host, the resulting go tool will be able to compile programs with all the architectures supported by gccgo.
```
$ cd ~/tmp
$ hg clone ~/src/go # [0]
$ cd go/src/cmd/go
$ go build -o xgo -compiler gccgo . # [1] [2] [3]
$ cp xgo ~/bin/ # Or any directory that is in your $PATH
```
* ` [0 `] Clone Go source to directory outside $GOROOT. Needed since the cmd/go we're about to compile is handles specially.
* ` [1 `] Here the _gccgo_ that targets **host** must be used, and not the cross-compiling gccgo. Make sure to have you _$PATH_ set correctly for this.
* ` [2 `] Will produce binary named xgo to distinguish from the existing go-binary. Name it to something suitable, e.g. mgo if your target is MIPS.
* ` [3 `] The compilation step (go build) can fail with some compilation errors since gccgo is lagging behind the go project (at least at go mercurial tip 7f2863716967). Fix those errors by commenting out or something more clever and re-compile.
## Cross-compile Go programs.
With your _$PATH_ set to find _xgo\_and the cross-compiling version of_gccgo and _$GOARCH_ set properly you can now cross-compile using the go tool (named xgo).
```
$ export PATH="path/to/xgo/:path/to/crosscomp-gccgo/:$PATH"
$ export GOARCH="<you-target's-arch>"
$ export GOOS="<you-target's-OS>"
$ xgo build -compiler gccgo <go-package/files>
```
## TODO
Go-programs importing "C" does not seems to work using xgo. Currently blocked by [Go issue#7398](https://code.google.com/p/go/issues/detail?id=7398)
This Wiki page was inspired by the lessons learned from "[golang-nuts] Simplification of MIPS cross-compilation?" @ https://groups.google.com/forum/#!topic/golang-nuts/PgyS2yoO2jM

110
GithubCodeLayout.md Normal file

@ -0,0 +1,110 @@
# Introduction
A common use case is to create a reusable library and an application that consumes it, and host both on Github. We will illustrate this with a trivial application called "` uselessd `" that consumes a likewise trivial library called "` useless `".
# Code Layout
The app and both libraries live on Github, each in its own repository. ` $GOPATH ` is the root of the _project_ - each of your Github repos will be checked out several folders below ` $GOPATH `.
Your code layout would look like this:
```
$GOPATH/
src/
github.com/
jmcvetta/
useless/
.git/
useless.go
useless_test.go
README.md
uselessd/
.git/
uselessd.go
uselessd_test.go
README.md
```
Each folder under ` src/github.com/jmcvetta/ ` is the root of a separate git checkout.
# $GOPATH
Your ` $GOPATH ` variable will point to the root of your Go workspace, as described in [How to Write Go Code](http://golang.org/doc/code.html).
# Note for Eclipse Users
Both Go and Eclipse use the term "workspace", but they use it to mean something different. What Go calls a "workspace" is what Eclipse calls a "project". Whenever this document uses either term, it refers to a Go workspace.
# Setup the Workspace
Let's assume we are starting from scratch. Initialize the two new repositories on Github, using the "Initialize this repository with a README" option so your repos can be cloned immediately. Then setup the project like this:
```sh
cd ~/workspace # Standard location for Eclipse workspace
mkdir mygo # Create your Go workspace
export GOPATH=~/workspace/mygo # GOPATH = Go workspace
cd $GOPATH
mkdir -p src/github.com/jmcvetta
cd src/github.com/jmcvetta
git clone git@github.com:jmcvetta/useless.git
git clone git@github.com:jmcvetta/uselessd.git
```
# Libraries
Conventionally, the name of the repository is the same as the name of the package it contains. Our ` useless ` repo contains ` useless.go ` which defines ` package useless `:
```Go
package useless
func Foobar() string {
return "Foobar!"
}```
# Applications
An application - Go code that will be compiled into an executable command - always defines ` package main ` with a ` main() ` function.
So ` uselessd.go ` looks like this:
```Go
package main
import (
"net/http"
"code.google.com/p/go.net/websocket"
"github.com/jmcvetta/useless"
)
func main() {
http.Handle("/useless", websocket.Handler(func(ws *websocket.Conn) {
ws.Write([]byte(useless.Foobar()))
}))
http.ListenAndServe(":3000", nil)
}```
# Dependencies
Your project will probably depend on some existing packages. The application above depends upon ` code.google.com/p/go.net/websocket `. You can install all dependencies by running "` go get -v ./... `" from the root of your workspace. The "` go get `" command is similar to "` go install `" in that it will attempt to build and install all packages in the workspace (technically, all packages matched by "` ./... `"), except that it will also examine their dependencies and download (and install) any that are missing first.
See the output of "` go help packages `" for a full explanation of the "` ... `" syntax.
All dependencies will be installed alongside your code under "` $GOPATH/src `". All Github reposities checked out by "` go get `" will be use the read-only ` https:// ` repository by default. To push changes back to github from one of these repositories, change the "` origin/master `" ref in ` .git/config ` to match the SSH repository from Github.
# Build
During development you can build the ` useless ` library by itself with the command "` go build ...useless `". You could also give the full path to the package name, "` go build github.com/jmcvetta/useless `".
To compile ` uselessd.go ` and its dependencies into an executable, use the command "` go build ...uselessd `".
# Example Code
FWIW all the repo addresses on this page are real, and the ` uselessd ` application should compile if you follow the directions above.

115
Go1point1Gotchas.md Normal file

@ -0,0 +1,115 @@
# Go 1.1 "gotchas"
While Go 1.1 is compatible with Go 1.0, the [compatibility promise](http://golang.org/doc/go1compat.html) permits the Go authors to break existing programs if they were incorrect in the first place.
Here are a few ways in which the bug fixes in Go 1.1 may have broken your Go programs.
## Unknown foo.Bar field in struct literal
Struct field names must not include package qualifiers.
For example, take this struct with an embedded ` *bytes.Buffer ` field:
```
type S struct {
*bytes.Buffer
}
```
In Go 1.0 the compiler would (incorrectly) accept this struct literal:
```
s := S{
bytes.Buffer: new(bytes.Buffer),
}
```
Under Go 1.1 the compiler rejects this.
Instead you should use the field name without the package qualifier:
```
s := S{
Buffer: new(bytes.Buffer),
}
```
## Initialization loop
The Go 1.1 compiler now better detects initialization loops.
For instance, the following code compiled under Go 1.0.
```
var funcVar = fn
func fn() {
funcVar()
}
```
Such code must now use an ` init ` function for the variable assignment to avoid
the initialization loop.
```
var funcVar func()
func fn() {
funcVar()
}
func init() {
funcVar = fn
}
```
In particular, this affects users of App Engine's [delay package](https://developers.google.com/appengine/docs/go/taskqueue/delay).
## Cannot fallthrough final case in switch
Go 1.0 permitted fallthrough in the final case of a switch statement:
```
switch {
case false:
fallthrough // fall through to 'true' case
case true:
fallthrough // fall through to... nowhere?
}
```
A language change affecting [return requirements](http://golang.org/doc/go1.1#return) led us to make the superfluous fallthrough illegal.
The fix is to remove such statements from your code.
## Duplicate argument name in parameters and return values
A compiler bug permitted function type declarations with parameters and return values of the same name. This would compile under Go 1.0:
```
type T func(a int) (a int)
```
Under Go 1.1, the compiler gives an error:
```
duplicate argument a
```
The fix is to rename the arguments so that they use different names.
## Package "go" forbidden
The import path "go" is now reserved. If you have a package in your workspace
whose import path is "go", you will need to rename it and move it somewhere
else.
While it was permitted, it is a bad idea to use this import path.
The standard library includes "go/parser", "go/ast", and so on.
It's posssible that a "go" package might be introduced in a future Go release,
making your "go" package unusable.
Please read [How to write Go code](http://golang.org/doc/code.html) for more
details about importh paths.

369
GoArm.md Normal file

@ -0,0 +1,369 @@
# Introduction
Go is fully supported on linux/arm. Any Go program that you can compile for x86/x86\_64 should work on Arm.
# Supported architectures
Go supports the following ARM architectural families.
| **Architecture** | **Status** | **GOARM value** | **Notes** |
|:-----------------|:-----------|:----------------|:----------|
| ARMv4 and below | sorry, not supported | n/a | |
| ARMv5 | supported | GOARM=5 | |
| ARMv6 | supported | | GOARM=6 is the default value|
| ARMv7 | supported | GOARM=7 | |
| ARMv8 | work in progress | n/a | contact aram for details |
Starting from Go 1.1, the appropriate GOARM value will be chosen if you compile Go from source on the target machine. In cross compilation situations, it is recommended that you always export an appropriate GOARM value.
# Supported operating systems
Go supports ARM on Linux. You must be running a [EABI](http://wiki.debian.org/ArmEabiPort) kernel. These are generally known as ` armel ` for softfloat (compatible with ARMv5) or ` armhf ` for hardware floating point (ARMv6 and above).
# Recommended Go version
The recommended minimum version for running Go on arm systems is Go 1.1.
# Tips and tricks
## /tmp and tmpfs
The ` go ` build tool uses ` /tmp ` when compiling and testing, this can cause heavy wear and tear if ` /tmp ` lives on your SD card. To minimise this effect, either ` export TMPDIR ` to somewhere that lives on another filesystem. Alternatively if you have lots of physical memory you can mount a swap backed tmpfs filesystem on /tmp by adding this line to ` /etc/fstab `
```
tmpfs /tmp tmpfs nodev,nosuid,mode=1777 0 0
```
## Swap
Building Go from source requires at least 256mb of RAM. Running the tests requires at least 256mb of memory and at least 512mb of swap space.
## Build failures due to lack of memory
The Go tool will try to keep all your cpu cores busy when installing packages (during make.bash),
this is normally preferable on PCs where memory is abundant.
However, some powerful multicore ARM machines don't have enough memory to support parallel
builds utilizing all available cores, and you can work around that by using the ` taskset(1) ` utility
to limit Go to only use one core without resorting to swaps.
```
taskset 1 ./make.bash # use 3 if you want to use two cores
```
Note: the 1 here is a bitmask for cpu affinity and it's not the number of cpu cores you're
willing to use, please refer to ` taskset(1) ` manual for details.
# Known issues
## Lack of floating point hardware on ARMv5
The major issue with ARMv5 is the lack of floating point support in common ARMv5 harware<sup></sup>. When compiled with the GOARM=5 environment variable, the 5l linker will insert a call to ` _sfloat ` before any block of floating point instructions to branch into the floating point emulator. This means that binaries produced with a Go installation that was compiled with soft float support will work on all supported architectures, but builds compiled without soft floating point support will not work on ARMv5.
<sup></sup> This isn't strictly true, there exist ARMv5 implementations which have VFP1 floating point. However the compiler doesn't support VFP1 yet.
## html/template and test/nilptr.go test fail on HTC Android
html/template test and test/nilptr.go is known to fail on HTC's Android kernels ([ref](http://www.mail-archive.com/android-developers@googlegroups.com/msg153389.html)), because the kernel will kill the application after 10 segfaults.
## Potential kernel bug in 2.6.32-5-kirkwood on QNAP 219P
See [Issue 5466](https://code.google.com/p/go/issues/detail?id=5466) for details. Updating to 3.2.0-4-kirkwood solved the issue.
# Success stories
ARM hardware comes in a myriad of shapes and sizes. If you've had a success story building and running Go on your Arm system, please detail your results here.
## Netgear Stora
Architecture: ARMv5
Operating System: Debian Sid
The Netgear Stora is an ARMv5 (Marvell Kirkwood) platform. I flashed mine with a Debian Sid distribution and it was, until Go1, a solid platform for Go development. The main drawback is the Stora only has 128mb of ram, which is not quite enough to run ./all.bash as 5l can use more than 100mb of ram when linking some commands.
Instructions for installing Debian on your Stora can be found on the OpenStora website, http://www.openstora.com/wiki/index.php?title=How_to_install_Debian_Linux_on_NETGEAR_Stora.
> _-- dave cheney_
## Qnap TS-119P II
Architecture: ARMv5
Operating System: Debian Squeeze
The Qnap TS series of NASs are excellent hackable little linux hosts. The TS-11P9 II is a 2Ghz Marvell Kirkwood ARMv5 processor with 512mb of ram and a single SATA drive bay.
The kirkwood platform is supported by the native debian installer. http://www.cyrius.com/debian/kirkwood/qnap/ts-119/install.html
> _-- dave cheney_
## Pandaboard
Architecture: ARMv7
Operating System: Ubuntu 12.04LTS (armhf)
The Pandaboard is a dual core ARMv7 development board based on the Texas Instruments OMAP4 SoC platform. I run ubuntu 12.04 LTS server on mine, which is an excellent distribution for Arm development. The Pandaboard has a gig of ram which makes it excellent for development and benchmarking.
Instructions and SD card image can be found on on the Ubuntu wiki, https://wiki.ubuntu.com/ARM/Server/Install#Installing_pre-installed_OMAP4_Precise_.2812.04.29_Server_Images.
> _-- dave cheney_
## BeagleBone
Architecture: ARMv7 single core, Cortex-A8, 256MB RAM, 720 MHz
Operating System: Angstrom Linux
BeagleBone is similar to Beagleboard, but without the video components. Angstrom is a very small Linux distribution for ARM based systems. It is built on top of Yocto and OpenEmbedded with additional tools and recipes to make it even easier to build a distribution. You can think of Angstrom as Ubuntu and OpenEmbedded/Yocto as Debian. Angstrom is very light weight and fast compared to Ubuntu. It uses systemd instead of the sys5 scripts which help give you a very fast boot time of a few seconds.
BeagleBone is probably faster than a RasberryPI because of it's newer Cortex-A8 dual-issue superscalar architecture, but the PI has the GPU which theoretically could be used with something like OpenCL to really run circles around the BeagleBone. However, for embedded applications the BeagleBone is easier to work with because it is ready out of the box with GPIO connections.
I've cross compiled for ARM with 5g from a Mac and so far I haven't run into any problems. You can build on the BeagleBone, but cross compiling with Go is so easy that it is better to save wear and tear on the flash drive and just compile somewhere else.
> _-- hans stimer_
### Zyxel NSA 310
Architecture: ARM5
Platform: Debian Wheeze
Successfuly built default branch, going to write fan control daemon for this device in golang.
### Raspberry Pi
Architecture: ARM1176JZFS, with floating point, running at 700Mhz
Operating System: Debian Wheezy beta distribution (http://www.raspberrypi.org/archives/1435) reported as:
` Linux raspberrypi 3.1.9+ #125 PREEMPT Sun Jun 17 16:09:36 BST 2012 armv6l GNU/Linux `
**Memory Split**: the Pi shares its 256mb of memory between the CPU and the GPU. You should allocate as much memory as possible to the CPU for a successful compilation. The configuration for the memory split is stored on your SD card. This link has a script to adjust the configuration, http://sirlagz.net/?p=445.
Go version weekly.2012-03-27 +645947213cac, with timeout and GOARM 7 patches http://codereview.appspot.com/5987063/) builds with 2 test failures: encoding/gob fails with out of memory, and fmt fails the NaN test.
Successfully installed and run SVGo via go get github.com/ajstarks/svgo, tested with goplay:
![http://farm8.staticflickr.com/7139/7451061716_fbb585c55f.jpg](http://farm8.staticflickr.com/7139/7451061716_fbb585c55f.jpg)
Division benchmark via http://codereview.appspot.com/6258067:
```
$ cd $GOROOT/src/pkg/runtime
$ go test -test.bench=BenchmarkUint
BenchmarkUint32Div7 5000000 547 ns/op
BenchmarkUint32Div37 5000000 547 ns/op
BenchmarkUint32Div123 5000000 547 ns/op
BenchmarkUint32Div763 5000000 547 ns/op
BenchmarkUint32Div1247 5000000 547 ns/op
BenchmarkUint32Div9305 5000000 547 ns/op
BenchmarkUint32Div13307 5000000 547 ns/op
BenchmarkUint32Div52513 5000000 547 ns/op
BenchmarkUint32Div60978747 5000000 547 ns/op
BenchmarkUint32Div106956295 5000000 547 ns/op
BenchmarkUint32Mod7 5000000 547 ns/op
BenchmarkUint32Mod37 5000000 547 ns/op
BenchmarkUint32Mod123 5000000 547 ns/op
BenchmarkUint32Mod763 5000000 547 ns/op
BenchmarkUint32Mod1247 5000000 547 ns/op
BenchmarkUint32Mod9305 5000000 547 ns/op
BenchmarkUint32Mod13307 5000000 547 ns/op
BenchmarkUint32Mod52513 5000000 547 ns/op
BenchmarkUint32Mod60978747 5000000 547 ns/op
BenchmarkUint32Mod106956295 5000000 547 ns/op
```
Running the hardware floating point distribution, Raspbian "pisces" (http://www.raspbian.org/PiscesImages) and applying the patches in https://gist.github.com/3116118, here are the results of the Eleanor McHugh gospeed benchmark:
```
raspbian@pisces:~/gowork/src/github.com/feyeleanor/gospeed$ uname -a
Linux pisces 3.1.9+ #171 PREEMPT Tue Jul 17 01:08:22 BST 2012 armv6l GNU/Linux
raspbian@pisces:~/gowork/src/github.com/feyeleanor/gospeed$ go test -test.bench=".*"
PASS
BenchmarkBaselineCastInt32ToInt 100000000 13.5 ns/op
BenchmarkBaselineCastIntToInt32 100000000 13.5 ns/op
BenchmarkBaselineCastInt64ToUint64 100000000 17.8 ns/op
BenchmarkBaselineCastUint64ToInt64 100000000 17.2 ns/op
BenchmarkBaselineVariableGet 100000000 13.4 ns/op
BenchmarkBaselineVariableSet 100000000 22.4 ns/op
BenchmarkBaselineVariableGetInterface 100000000 13.5 ns/op
BenchmarkBaselineVariableSetInterface 50000000 31.3 ns/op
BenchmarkBaselineVariableIncrement 100000000 23.9 ns/op
BenchmarkBaselineVariableDecrement 100000000 23.9 ns/op
BenchmarkBaselineFieldGet 100000000 13.5 ns/op
BenchmarkBaselineFieldSet 100000000 20.9 ns/op
BenchmarkBaselineSliceGet 50000000 32.9 ns/op
BenchmarkBaselineSliceSet 50000000 34.5 ns/op
BenchmarkBaselineMapIntGet 1000000 1448 ns/op
BenchmarkBaselineMapIntSet 1000000 1968 ns/op
BenchmarkBaselineMapStringGet 1000000 1119 ns/op
BenchmarkBaselineMapStringSet 1000000 1675 ns/op
BenchmarkBaselineIf 100000000 15.0 ns/op
BenchmarkBaselineIfElse 100000000 15.0 ns/op
BenchmarkBaselineSwitchDefault 100000000 13.5 ns/op
BenchmarkBaselineSwitchOneCase 100000000 15.0 ns/op
BenchmarkBaselineSwitchTwoCases 100000000 18.0 ns/op
BenchmarkBaselineSwitchTwoCasesFallthrough 100000000 18.0 ns/op
BenchmarkBaselineForLoopIteration 50000000 42.0 ns/op
BenchmarkBaselineForReverseLoopIteration 50000000 36.0 ns/op
BenchmarkBaselineForRange 20000000 80.9 ns/op
BenchmarkBaselineForSliceLength 50000000 39.0 ns/op
BenchmarkBaselineForReverseSliceLength 50000000 36.0 ns/op
BenchmarkBaselineForLoopIteration10 20000000 119 ns/op
BenchmarkBaselineForReverseLoopIteration10 20000000 92.9 ns/op
BenchmarkBaselineForRange10 10000000 215 ns/op
BenchmarkBaselineForSliceLength10 20000000 109 ns/op
BenchmarkBaselineForReverseSliceLength10 20000000 92.9 ns/op
BenchmarkBaselineForLoopIteration100 2000000 929 ns/op
BenchmarkBaselineForReverseLoopIteration100 5000000 700 ns/op
BenchmarkBaselineForRange100 1000000 1567 ns/op
BenchmarkBaselineForSliceLength100 2000000 853 ns/op
BenchmarkBaselineForReverseSliceLength100 5000000 700 ns/op
BenchmarkBaselineForLoopIteration10000 10000 106006 ns/op
BenchmarkBaselineForReverseLoopIteration10000 50000 67480 ns/op
BenchmarkBaselineForRange10000 10000 153841 ns/op
BenchmarkBaselineForSliceLength10000 20000 85735 ns/op
BenchmarkBaselineForReverseSliceLength10000 50000 69461 ns/op
BenchmarkBaselineMakeChannelBoolUnbuffered 200000 10162 ns/op
BenchmarkBaselineMakeChannelBool1 200000 12517 ns/op
BenchmarkBaselineMakeChannelBool10 200000 12521 ns/op
BenchmarkBaselineMakeChannelStringUnbuffered 500000 10369 ns/op
BenchmarkBaselineMakeChannelString1 200000 12576 ns/op
BenchmarkBaselineMakeChannelString10 100000 22358 ns/op
BenchmarkBaselineGo 50000 367593 ns/op
BenchmarkBaselineFunctionCall 50000000 57.0 ns/op
BenchmarkBaselineFunctionCallArg 20000000 81.0 ns/op
BenchmarkBaselineFunctionCall5VarArgs 500000 6852 ns/op
BenchmarkBaselineFunctionCallInt 50000000 60.3 ns/op
BenchmarkBaselineFunctionCall5VarInts 1000000 3185 ns/op
BenchmarkBaselineFunctionCallWithDefer 1000000 2330 ns/op
BenchmarkBaselineFunctionCallPanicRecover 500000 6222 ns/op
BenchmarkBaselineMethodCallDirect 20000000 83.8 ns/op
BenchmarkBaselineMethodCallDirect1Arg 20000000 106 ns/op
BenchmarkBaselineMethodCallDirect1Int 20000000 85.2 ns/op
BenchmarkBaselineMethodCallDirect5Args 5000000 368 ns/op
BenchmarkBaselineMethodCallDirect5Ints 10000000 233 ns/op
BenchmarkBaselineMethodCallIndirect 100000000 18.0 ns/op
BenchmarkBaselineMethodCallIndirect1Arg 50000000 42.0 ns/op
BenchmarkBaselineMethodCallIndirect1Int 100000000 19.5 ns/op
BenchmarkBaselineMethodCallIndirect5Args 5000000 309 ns/op
BenchmarkBaselineMethodCallIndirect5Ints 10000000 168 ns/op
BenchmarkBaselineTypeAssertion 10000000 218 ns/op
BenchmarkBaselineTypeAssertionEmptyInterface 20000000 106 ns/op
BenchmarkBaselineTypeAssertionInterface1 5000000 576 ns/op
BenchmarkBaselineTypeAssertionInterface2 5000000 579 ns/op
BenchmarkBaselineTypeReflectPrimitiveToValue 5000000 425 ns/op
BenchmarkBaselineTypeReflectSliceToValue 1000000 3218 ns/op
BenchmarkBaselineTypeReflectStructToValue 500000 4760 ns/op
BenchmarkBaselineTypeCheck 10000000 189 ns/op
BenchmarkBaselineTypeCheckEmptyInterface 20000000 93.1 ns/op
BenchmarkBaselineTypeCheckInterface1 5000000 511 ns/op
BenchmarkBaselineTypeCheckInterface2 5000000 516 ns/op
BenchmarkBaselineTypeSwitchOneCase 10000000 262 ns/op
BenchmarkBaselineTypeSwitchBasicTypesCase 10000000 295 ns/op
BenchmarkBaselineTypeSwitchEmptyInterface 10000000 163 ns/op
BenchmarkBaselineTypeSwitchInterface1 5000000 588 ns/op
BenchmarkBaselineTypeSwitchInterface2 5000000 602 ns/op
BenchmarkBaselineNewStructureLiteral 20000000 84.0 ns/op
BenchmarkBaselineNewStructure 20000000 127 ns/op
BenchmarkBaselineNewSliceLiteral 50000000 54.2 ns/op
BenchmarkBaselineNewSlice 1000000 3124 ns/op
BenchmarkBaselineNewMapLiteralIntToInt 500000 9083 ns/op
BenchmarkBaselineNewMapLiteralIntToInterface 500000 9807 ns/op
BenchmarkBaselineNewMapLiteralStringToInt 500000 9792 ns/op
BenchmarkBaselineNewMapLiteralStringToInterface 500000 10595 ns/op
BenchmarkBaselineNewMapLiteralIntToInt2Item 200000 14265 ns/op
BenchmarkBaselineNewMapLiteralIntToInterface2Item 200000 14669 ns/op
BenchmarkBaselineNewMapLiteralStringToInt2Item 200000 14025 ns/op
BenchmarkBaselineNewMapLiteralStringToInterface2Item 200000 15086 ns/op
BenchmarkBaselineNewMapIntToInt 500000 9025 ns/op
BenchmarkBaselineNewMapIntToInterface 500000 9753 ns/op
BenchmarkBaselineNewMapStringToInt 500000 9740 ns/op
BenchmarkBaselineNewMapStringToInterface 500000 10486 ns/op
BenchmarkBaselineSliceCopy 5000000 300 ns/op
BenchmarkBaselineNewSliceAppendElement1 1000000 3318 ns/op
BenchmarkBaselineNewSliceAppendElement10 1000000 5174 ns/op
ok github.com/feyeleanor/gospeed 417.296s
```
_-- anthony starks_
## ODROID-X
Architecture: ARMv7 quad-core Cortex-A9 (Samsung Exynos 4412 1.4GHz), 1GB RAM, Mali graphics (untested).
Operating System: [Archlinux ARM](http://archlinuxarm.org/)
Go pre-1.1 compiles out of the box. The four cores make it particularly suited to Go multi-threaded programs. An ODROID-X2 is coming (Nov 2012) with more RAM.
_-- Rémy Oudompheng_
## BananaPi
[BananaPi](http://bananapi.org) has a few enhanced hardware components compare with Raspberry Pi.
| **Architecture** | **Comments** |
|:-----------------|:-------------|
| [Allwinner A20(ARM Cortex-A7 Dual-core, 1GHz, Mali400MP2 GPU)](http://www.allwinnertech.com/en/clq/processora/A20.html) | tbc |
| eSATA | No worry to wear out your root SD Card|
| Onboard Microphone | tbc |
| 1G Etherenet | tbc |
| 1G RAM | tbc |
| Reset Switch | To reset the board ?|
| Power Switch | To power cycle the board ?|
```
root@bpi01:/data/go13/src# cat ./buildgo.bash
#!/bin/bash
# use 1 CPU to avoid out of memory compilation issue.
time taskset 2 ./make.bash
root@bpi01:/data/go13/src# ./buildgo.bash
<snipped>
Installed Go for linux/arm in /data/go1.3
Installed commands in /data/go1.3/bin
real 9m9.222s
user 8m18.960s
sys 0m40.920s
root@bpi01:/data/go1.3/src#
```
_--T.J. Yang_
## AppliedMicro X-Gene (ARMv8)
Architecture: ARMv8 (64-bit) 8-core, 2.4GHz, 16GB RAM
Operating System: Linux
The linux/arm64 Go port is not functional yet, but you can run the linux/arm port.
```
$ sudo apt-get install gcc-arm-linux-gnueabihf libc6-dev-armhf-cross
$
$ cd go/src && CC='arm-linux-gnueabihf-gcc -static' GO_DISTFLAGS=-s GOHOSTARCH=arm GOARM=7 CGO_ENABLED=0 ./make.bash
$
$ uname -a
Linux xgene 3.16.0-25-generic #33-Ubuntu SMP Tue Nov 4 12:06:56 UTC 2014 aarch64 aarch64 aarch64 GNU/Linux
$ go version
go version devel +6a8045fd9da9 Wed Dec 03 18:33:35 2014 +0100 linux/arm
$ go env
GOARCH="arm"
GOBIN=""
GOCHAR="5"
GOEXE=""
GOHOSTARCH="arm"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/aram"
GORACE=""
GOROOT="/home/aram/go"
GOTOOLDIR="/home/aram/go/pkg/tool/linux_arm"
CC="arm-linux-gnueabihf-gcc"
GOGCCFLAGS="-static -fPIC -marm -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"
```
A static toolchain is required as arm64 Linux distributions don't ship the necessary 32-bit arm libraries (except in a sysroot). ` GO_DISTFLAGS=-s ` is not enough, ` CC='arm-linux-gnueabihf-gcc -static' ` is required to build a static dist tool.
_-- Aram Hăvărneanu_

864
GoForCPPProgrammers.md Normal file

@ -0,0 +1,864 @@
Go is a systems programming language intended to be a general-purpose systems
language, like C++. These are some notes on Go for experienced C++
programmers. This document discusses the differences between Go and C++, and
says little to nothing about the similarities.
An important point to keep in mind is that there are some fundamental differences in the thought processes required to be proficient in the two respective languages. Most formidably, C++'s object model is based on classes and class hierarchies while Go's object model is based on interfaces (and is essentially flat). Consequently, C++ design patterns rarely translate verbatim to Go. To program effectively in Go, one has to consider the _problem_ being solved, not the mechanisms one might use in C++ to solve the problem.
For a more general introduction to Go, see the
<a href='http://tour.golang.org/'>Go Tour</a>,
<a href='http://golang.org/doc/code.html'>How to Write Go Code</a>
and <a href='http://golang.org/doc/effective_go.html'>Effective Go</a>.
For a detailed description of the Go language, see the
<a href='http://golang.org/doc/go_spec.html'>Go spec</a>.
<h2>Conceptual Differences</h2>
<ul>
<li>Go does not have classes with constructors or destructors. Instead of<br>
class methods, a class inheritance hierarchy, and virtual functions, Go<br>
provides <em>interfaces</em>, which are discussed in more detail below.<br>
Interfaces are also used where C++ uses templates.</li>
<li>Go provides automatic garbage collection of allocated memory. It is not necessary (or possible) to release memory explicitly. There is no need to worry about heap-allocated vs. stack-allocated storage, <code>new</code> vs. <code>malloc</code>, or <code>delete</code> vs. <code>delete[]</code> vs. <code>free</code>. There is no need to separately manage <code>std::unique_ptr</code>, <code>std::shared_ptr</code>, <code>std::weak_ptr</code>, <code>std::auto_ptr</code>, and ordinary, "dumb" pointers. Go's run-time system handles all of that error-prone code on the programmer's behalf.</li>
<li>Go has pointers but not pointer arithmetic. Go pointers therefore more closely resemble C++ references. One cannot use a Go pointer<br>
variable to walk through the bytes of a string, for example. Slices, discussed further below, satisfy most of the need for pointer arithmetic.</li>
<li>Go is "safe" by default. Pointers cannot point to arbitrary memory, and buffer overruns result in crashes, not security exploits. The <code>unsafe</code> package lets programmers bypass some of Go's protection mechanisms where explicitly requested.</li>
<li>Arrays in Go are first class values. When an array is used as a function<br>
parameter, the function receives a copy of the array, not a pointer to it.<br>
However, in practice functions often use slices for parameters; slices hold<br>
pointers to underlying arrays. Slices are discussed further below.</li>
<li>Strings are provided by the language. They may not be changed once they<br>
have been created.</li>
<li>Hash tables are provided by the language. They are called maps.</li>
<li>Separate threads of execution, and communication channels between them, are<br>
provided by the language. This is discussed further below.</li>
<li>Certain types (maps and channels, described further below) are passed by<br>
reference, not by value. That is, passing a map to a function does not copy the<br>
map, and if the function changes the map the change will be seen by the caller.<br>
In C++ terms, one can think of these as being reference types.</li>
<li>Go does not use header files. Instead, each source file is part of a<br>
defined <em>package</em>. When a package defines an object (type, constant,<br>
variable, function) with a name starting with an upper case letter, that object<br>
is visible to any other file which imports that package.</li>
<li>Go does not support implicit type conversion. Operations that mix different types require casts (called conversions in Go). This is true even of different user-defined aliases of the same underlying type.</li>
<li>Go does not support function overloading and does not support user defined<br>
operators.</li>
<li>Go does not support <code>const</code> or <code>volatile</code> qualifiers.</li>
<li>Go uses <code>nil</code> for invalid pointers, where C++ uses <code>NULL</code> or simply <code>0</code> (or in C++11, <code>nullptr</code>).</li>
<li>Idiomatic Go uses multiple return values to convey errors—one or more data results plus an error code—instead of sentinel values (e.g., <code>-1</code>) or structured exception handling (C++'s <code>try</code><code>catch</code> and <code>throw</code> or Go's <code>panic</code><code>recover</code>).</li>
</ul>
<h2>Syntax</h2>
The declaration syntax is reversed compared to C++. You write the name
followed by the type. Unlike in C++, the syntax for a type does not match
the way in which the variable is used. Type declarations may be read
easily from left to right. (` var v1 int ` → "Variable ` v1 ` is an ` int `.")
```
Go C++
var v1 int // int v1;
var v2 string // const std::string v2; (approximately)
var v3 [10]int // int v3[10];
var v4 []int // int* v4; (approximately)
var v5 struct { f int } // struct { int f; } v5;
var v6 *int // int* v6; (but no pointer arithmetic)
var v7 map[string]int // unordered_map<string, int>* v7; (approximately)
var v8 func(a int) int // int (*v8)(int a);
```
Declarations generally take the form of a keyword followed by the name
of the object being declared. The keyword is one of ` var `,
` func `,
` const `, or ` type `. Method declarations are a minor
exception in that
the receiver appears before the name of the object being declared; see
the <a href='#Interfaces'>discussion of interfaces</a>.
You can also use a keyword followed by a series of declarations in
parentheses.
```
var (
i int
m float64
)
```
When declaring a function, you must either provide a name for each parameter
or not provide a name for any parameter. (That is, C++ permits ` void f(int i, int); `, but Go does not permit the analogous ` func f(i int, int) `.) However, for convenience, in Go you may group several names with the same type:
```
func f(i, j, k int, s, t string)
```
A variable may be initialized when it is declared. When this is done,
specifying the type is permitted but not required. When the type is
not specified, the type of the variable is the type of the
initialization expression.
```
var v = *p
```
See also the <a href='#Constants'>discussion of constants, below</a>.
If a variable is not initialized explicitly, the type must be specified.
In that case it will be
implicitly initialized to the type's zero value
(` 0 `, ` nil `, etc.). There are no
uninitialized variables in Go.
Within a function, a short declaration syntax is available with
` := ` .
```
v1 := v2 // C++11: auto v1 = v2;
```
This is equivalent to
```
var v1 = v2 // C++11: auto v1 = v2;
```
Go permits multiple assignments, which are done in parallel. That is, first all of the values on the right-hand side are computed, and then these values are assigned to the variables on the left-hand side.
```
i, j = j, i // Swap i and j.
```
Functions may have multiple return values, indicated by a list in
parentheses. The returned values can be stored by assignment
to a list of variables.
```
func f() (i int, j int) { ... }
v1, v2 = f()
```
Multiple return values are Go's primary mechanism for error handling:
```
result, ok := g()
if !ok {
// Something bad happened.
return nil
}
// Continue as normal.
```
or, more tersely,
```
if result, ok := g(); !ok {
// Something bad happened.
return nil
}
// Continue as normal.
```
Go code uses very few semicolons in practice. Technically, all Go
statements are terminated by a semicolon. However, Go treats the end
of a non-blank line as a semicolon unless the line is clearly
incomplete (the exact rules are
in <a href='go_spec.html#Semicolons'>the language specification</a>).
A consequence of this is that in some cases Go does not permit you to
use a line break. For example, you may not write
```
func g()
{ // INVALID
}
```
A semicolon will be inserted after ` g() `, causing it to be
a function declaration rather than a function definition. Similarly,
you may not write
```
if x {
}
else { // INVALID
}
```
A semicolon will be inserted after the ` } ` preceding
the ` else `, causing a syntax error.
Since semicolons do end statements, you may continue using them as in
C++. However, that is not the recommended style. Idiomatic Go code
omits unnecessary semicolons, which in practice is all of them other
than the initial ` for ` loop clause and cases where you want several
short statements on a single line.
While we're on the topic, we recommend that rather than worry about
semicolons and brace placement, you format your code with
the ` gofmt ` program. That will produce a single standard
Go style, and let you worry about your code rather than your
formatting. While the style may initially seem odd, it is as good as
any other style, and familiarity will lead to comfort.
When using a pointer to a struct, you use ` . ` instead
of ` -> `.
Thus, syntactically speaking, a structure and a pointer to a structure
are used in the same way.
```
type myStruct struct { i int }
var v9 myStruct // v9 has structure type
var p9 *myStruct // p9 is a pointer to a structure
f(v9.i, p9.i)
```
Go does not require parentheses around the condition of an ` if `
statement, or the expressions of a ` for ` statement, or the value of a
` switch ` statement. On the other hand, it does require curly braces
around the body of an ` if ` or ` for ` statement.
```
if a < b { f() } // Valid
if (a < b) { f() } // Valid (condition is a parenthesized expression)
if (a < b) f() // INVALID
for i = 0; i < 10; i++ {} // Valid
for (i = 0; i < 10; i++) {} // INVALID
```
Go does not have a ` while ` statement nor does it have a
` do/while `
statement. The ` for ` statement may be used with a single condition,
which makes it equivalent to a ` while ` statement. Omitting the
condition entirely is an endless loop.
Go permits ` break ` and ` continue ` to specify a label.
The label must
refer to a ` for `, ` switch `, or ` select `
statement.
In a ` switch ` statement, ` case ` labels do not fall
through. You can
make them fall through using the ` fallthrough ` keyword. This applies
even to adjacent cases.
```
switch i {
case 0: // empty case body
case 1:
f() // f is not called when i == 0!
}
```
But a ` case ` can have multiple values.
```
switch i {
case 0, 1:
f() // f is called if i == 0 || i == 1.
}
```
The values in a ` case ` need not be constants--or even integers;
any type
that supports the equality comparison operator, such as strings or
pointers, can be used--and if the ` switch `
value is omitted it defaults to ` true `.
```
switch {
case i < 0:
f1()
case i == 0:
f2()
case i > 0:
f3()
}
```
The ` defer ` statement may be used to call a function after the function containing the ` defer ` statement returns. ` defer ` often takes the place of a destructor in C++ but is associated with the calling code, not any particular class or object.
```
fd := open("filename")
defer close(fd) // fd will be closed when this function returns.
```
<h2>Operators</h2>
The ` ++ ` and ` -- ` operators may only be used in
statements, not in expressions.
You cannot write ` c = *p++ `. ` *p++ ` is parsed as
` (*p)++ `.
The operator precedence is different. As an example ` 4 & 3 << 1 ` evaluates to ` 0 ` in Go and ` 4 ` in C++.
```
Go operator precedence:
1. * / % << >> & &^
2. + - | ^
3. == != < <= > >=
4. &&
5. ||
```
```
C++ operator precedence (only relevant operators):
1. * / %
2. + -
3. << >>
4. < <= > >=
5. == !=
6. &
7. ^
8. |
9. &&
10. ||
```
<h2>Constants </h2>
In Go constants may be <i>untyped</i>. This applies even to constants
named with a ` const ` declaration, if no
type is given in the declaration and the initializer expression uses only
untyped constants.
A value derived from an untyped constant becomes typed when it
is used within a context that
requires a typed value. This permits constants to be used relatively
freely without requiring general implicit type conversion.
```
var a uint
f(a + 1) // untyped numeric constant "1" becomes typed as uint
```
The language does not impose any limits on the size of an untyped
numeric constant or constant expression. A limit is only applied when
a constant is used where a type is required.
```
const huge = 1 << 100
f(huge >> 98)
```
Go does not support enums. Instead, you can use the special name
` iota ` in a single ` const ` declaration to get a
series of increasing
value. When an initialization expression is omitted for a ` const `,
it reuses the preceding expression.
```
const (
red = iota // red == 0
blue // blue == 1
green // green == 2
)
```
<h2>Types</h2>
C++ and Go provide similar, but not identical, built-in types: signed and unsigned integers of various widths, 32-bit and 64-bit floating-point numbers (real and complex), ` struct `s, pointers, etc. In Go, ` uint8 `, ` int64 `, and like-named integer types are part of the language, not built on top of integers whose sizes are implementation-dependent (e.g., ` long long `). Go additionally provides native ` string `, ` map `, and ` channel ` types as well as first-class arrays and slices (described below). Strings are encoded with Unicode, not ASCII.
Go is far more strongly typed than C++. In particular, there is no implicit type coercion in Go, only explicit type conversion. This provides additional safety and freedom from a class of bugs but at the cost of some additional typing. There is also no ` union ` type in Go, as this would enable subversion of the type system. However, a Go ` interface{} ` (see below) provides a type-safe alternative.
Both C++ and Go support type aliases (` typedef ` in C++, ` type ` in Go). However, unlike C++, Go treats these as different types. Hence, the following is valid in C++:
```
// C++
typedef double position;
typedef double velocity;
position pos = 218.0;
velocity vel = -9.8;
pos += vel;
```
but the equivalent is invalid in Go without an explicit type conversion:
```
type position float64
type velocity float64
var pos position = 218.0
var vel velocity = -9.8
pos += vel // INVALID: mismatched types position and velocity
// pos += position(vel) // Valid
```
The same is true even for unaliased types: an ` int ` and a ` uint ` cannot be combined in an expression without explicitly converting one to the other.
Go does not allow pointers to be cast to and from integers, unlike in C++. However, Go's ` unsafe ` package enables one to explicitly bypass this safety mechanism if necessary (e.g., for use in low-level systems code).
<h2>Slices</h2>
A slice is conceptually a struct with three fields: a
pointer to an array, a length, and a capacity.
Slices support
the ` [] ` operator to access elements of the underlying array.
The builtin
` len ` function returns the
length of the slice. The builtin ` cap ` function returns the
capacity.
Given an array, or another slice, a new slice is created via
` a[i:j] `. This
creates a new slice which refers to ` a `, starts at
index ` i `, and ends before index
` j `. It has length ` j-i `.
If ` i ` is omitted, the slice starts at ` 0 `.
If ` j ` is omitted, the slice ends at ` len(a) `.
The new slice refers to the same array
to which ` a `
refers. Two implications of this statement are that ① changes made using the new slice may be seen using
` a `, and ② slice creation is (intended to be) cheap; no copy needs to be made of the underlying array. The
capacity of the new slice is simply the capacity of ` a ` minus
` i `. The capacity
of an array is the length of the array.
What this means is that Go uses slices for some cases where C++ uses pointers.
If you create a value of type ` [100]byte ` (an array of 100 bytes,
perhaps a
buffer) and you want to pass it to a function without copying it, you should
declare the function parameter to have type ` []byte `, and
pass a slice of the array (` a[:] ` will pass the entire array).
Unlike in C++, it is not
necessary to pass the length of the buffer; it is efficiently accessible via
` len `.
The slice syntax may also be used with a string. It returns a new string,
whose value is a substring of the original string.
Because strings are immutable, string slices can be implemented
without allocating new storage for the slices's contents.
<h2>Making values</h2>
Go has a builtin function ` new ` which takes a type and
allocates space
on the heap. The allocated space will be zero-initialized for the type.
For example, ` new(int) ` allocates a new int on the heap,
initializes it with the value ` 0 `,
and returns its address, which has type ` *int `.
Unlike in C++, ` new ` is a function, not an operator;
` new int ` is a syntax error.
Perhaps surprisingly, ` new ` is not commonly used in Go
programs. In Go taking the address of a variable is always safe and
never yields a dangling pointer. If the program takes the address of
a variable, it will be allocated on the heap if necessary. So these
functions are equivalent:
```
type S { I int }
func f1() *S {
return new(S)
}
func f2() *S {
var s S
return &s
}
func f3() *S {
// More idiomatic: use composite literal syntax.
return &S{}
}
```
In contrast, it is not safe in C++ to return a pointer to a local variable:
```
// C++
S* f2() {
S s;
return &s; // INVALID -- contents can be overwritten at any time
}
```
Map and channel values must be allocated using the builtin function
` make `.
A variable declared with map or channel type without an initializer will be
automatically initialized to ` nil `.
Calling ` make(map[int]int) ` returns a newly allocated value of
type ` map[int]int `.
Note that ` make ` returns a value, not a pointer. This is
consistent with
the fact that map and channel values are passed by reference. Calling
` make ` with
a map type takes an optional argument which is the expected capacity of the
map. Calling ` make ` with a channel type takes an optional
argument which sets the
buffering capacity of the channel; the default is 0 (unbuffered).
The ` make ` function may also be used to allocate a slice.
In this case it
allocates memory for the underlying array and returns a slice referring to it.
There is one required argument, which is the number of elements in the slice.
A second, optional, argument is the capacity of the slice. For example,
` make([]int, 10, 20) `. This is identical to
` new([20]int)[0:10] `. Since
Go uses garbage collection, the newly allocated array will be discarded
sometime after there are no references to the returned slice.
<h2>Interfaces</h2>
Where C++ provides classes, subclasses and templates,
Go provides interfaces. A
Go interface is similar to a C++ pure abstract class: a class with no
data members, with methods which are all pure virtual. However, in
Go, any type which provides the methods named in the interface may be
treated as an implementation of the interface. No explicitly declared
inheritance is required. The implementation of the interface is
entirely separate from the interface itself.
A method looks like an ordinary function definition, except that it
has a <em>receiver</em>. The receiver is similar to
the ` this ` pointer in a C++ class method.
```
type myType struct { i int }
func (p *myType) Get() int { return p.i }
```
This declares a method ` Get ` associated with ` myType `.
The receiver is named ` p ` in the body of the function.
Methods are defined on named types. If you convert the value
to a different type, the new value will have the methods of the new type,
not the old type.
You may define methods on a builtin type by declaring a new named type
derived from it. The new type is distinct from the builtin type.
```
type myInteger int
func (p myInteger) Get() int { return int(p) } // Conversion required.
func f(i int) { }
var v myInteger
// f(v) is invalid.
// f(int(v)) is valid; int(v) has no defined methods.
```
Given this interface:
```
type myInterface interface {
Get() int
Set(i int)
}
```
we can make ` myType ` satisfy the interface by adding
```
func (p *myType) Set(i int) { p.i = i }
```
Now any function which takes ` myInterface ` as a parameter
will accept a
variable of type ` *myType `.
```
func GetAndSet(x myInterface) {}
func f1() {
var p myType
GetAndSet(&p)
}
```
In other words, if we view ` myInterface ` as a C++ pure abstract
base
class, defining ` Set ` and ` Get ` for
` *myType ` made ` *myType ` automatically
inherit from ` myInterface `. A type may satisfy multiple interfaces.
An anonymous field may be used to implement something much like a C++ child
class.
```
type myChildType struct { myType; j int }
func (p *myChildType) Get() int { p.j++; return p.myType.Get() }
```
This effectively implements ` myChildType ` as a child of
` myType `.
```
func f2() {
var p myChildType
GetAndSet(&p)
}
```
The ` set ` method is effectively inherited from
` myType `, because
methods associated with the anonymous field are promoted to become methods
of the enclosing type. In this case, because ` myChildType ` has an
anonymous field of type ` myType `, the methods of
` myType ` also become methods of ` myChildType `.
In this example, the ` Get ` method was
overridden, and the ` Set ` method was inherited.
This is not precisely the same as a child class in C++.
When a method of an anonymous field is called,
its receiver is the field, not the surrounding struct.
In other words, methods on anonymous fields are not virtual functions.
When you want the equivalent of a virtual function, use an interface.
A variable that has an interface type may be converted to have a
different interface type using a special construct called a type assertion.
This is implemented dynamically
at run time, like C++ ` dynamic_cast `. Unlike
` dynamic_cast `, there does
not need to be any declared relationship between the two interfaces.
```
type myPrintInterface interface {
Print()
}
func f3(x myInterface) {
x.(myPrintInterface).Print() // type assertion to myPrintInterface
}
```
The conversion to ` myPrintInterface ` is entirely dynamic.
It will
work as long as the underlying type of x (the <em>dynamic type</em>) defines
a ` print ` method.
Because the conversion is dynamic, it may be used to implement generic
programming similar to templates in C++. This is done by
manipulating values of the minimal interface.
```
type Any interface { }
```
Containers may be written in terms of ` Any `, but the caller
must unbox using a type assertion to recover
values of the contained type. As the typing is dynamic rather
than static, there is no equivalent of the way that a C++ template may
inline the relevant operations. The operations are fully type-checked
at run time, but all operations will involve a function call.
```
type Iterator interface {
Get() Any
Set(v Any)
Increment()
Equal(arg Iterator) bool
}
```
Note that ` Equal ` has an argument of
type ` Iterator `. This does not behave like a C++
template. See <a href='go_faq.html#t_and_equal_interface'>the<br>
FAQ</a>.
<h2>Function closures</h2>
In C++ versions prior to C++11, the most common way to create a function with hidden state is to use a "functor"—a class that overloads ` operator() ` to make instances look like functions. For example, the following code defines a ` my_transform ` function (a simplified version of the STL's ` std::transform `) that applies a given unary operator (` op `) to each element of an array (` in `), storing the result in another array (` out `). To implement a prefix sum (i.e., {` x[0] `, ` x[0]+x[1] `, ` x[0]+x[1]+x[2] `, …}) the code creates a functor (` MyFunctor `) that keeps track of the running total (` total `) and passes an instance of this functor to ` my_transform `.
```
// C++
#include <iostream>
#include <cstddef>
template <class UnaryOperator>
void my_transform (size_t n_elts, int* in, int* out, UnaryOperator op)
{
size_t i;
for (i = 0; i < n_elts; i++)
out[i] = op(in[i]);
}
class MyFunctor {
public:
int total;
int operator()(int v) {
total += v;
return total;
}
MyFunctor() : total(0) {}
};
int main (void)
{
int data[7] = {8, 6, 7, 5, 3, 0, 9};
int result[7];
MyFunctor accumulate;
my_transform(7, data, result, accumulate);
std::cout << "Result is [ ";
for (size_t i = 0; i < 7; i++)
std::cout << result[i] << ' ';
std::cout << "]\n";
return 0;
}
```
C++11 adds anonymous ("lambda") functions, which can be stored in variables and passed to functions. They can optionally serve as closures, meaning they can reference state from parent scopes. This feature greatly simplifies ` my_transform `:
```
// C++11
#include <iostream>
#include <cstddef>
#include <functional>
void my_transform (size_t n_elts, int* in, int* out, std::function<int(int)> op)
{
size_t i;
for (i = 0; i < n_elts; i++)
out[i] = op(in[i]);
}
int main (void)
{
int data[7] = {8, 6, 7, 5, 3, 0, 9};
int result[7];
int total = 0;
my_transform(7, data, result, [&total] (int v) {
total += v;
return total;
});
std::cout << "Result is [ ";
for (size_t i = 0; i < 7; i++)
std::cout << result[i] << ' ';
std::cout << "]\n";
return 0;
}
```
A typical Go version of ` my_transform ` looks a lot like the C++11 version:
```
package main
import "fmt"
func my_transform(in []int, xform func(int) int) (out []int) {
out = make([]int, len(in))
for idx, val := range in {
out[idx] = xform(val)
}
return
}
func main() {
data := []int{8, 6, 7, 5, 3, 0, 9}
total := 0
fmt.Printf("Result is %v\n", my_transform(data, func(v int) int {
total += v
return total
}))
}
```
(Note that we chose to return ` out ` from ` my_transform ` rather than pass it an ` out ` to write to. This was an aesthetic decision; the code could have been written more like the C++ version in that regard.)
In Go, functions are always full closures, the equivalent of ` [&] ` in C++11. An important difference is that it is invalid in C++11 for a closure to reference a variable whose scope has gone away (as may be caused by an <a href='http://en.wikipedia.org/wiki/Funarg_problem'>upward funarg</a>—a function that returns a lambda that references local variables). In Go, this is perfectly valid.
<h2>Concurrency</h2>
Like C++11's ` std::thread `, Go permits starting new threads of execution that run concurrently in a shared address space. These are called _goroutines_ and are spawned using the ` go ` statement. While typical ` std::thread ` implementations launch heavyweight, operating-system threads, goroutines are implemented as lightweight, user-level threads that are multiplexed among multiple operating-system threads. Consequently, goroutines are (intended to be) cheap and can be used liberally throughout a program.
```
func server(i int) {
for {
fmt.Print(i)
time.Sleep(10 * time.Second)
}
}
go server(1)
go server(2)
```
(Note that the ` for ` statement in the ` server `
function is equivalent to a C++ ` while (true) ` loop.)
Function literals (which Go implements as closures)
can be useful with the ` go ` statement.
```
var g int
go func(i int) {
s := 0
for j := 0; j < i; j++ { s += j }
g = s
}(1000) // Passes argument 1000 to the function literal.
```
Like C++11, but unlike prior versions of C++, Go defines a
<a href='http://golang.org/ref/mem'>memory model</a> for unsynchronized accesses to memory. Although Go provides an analogue of ` std::mutex ` in its ` sync ` package, this is not the normal way to implement inter-thread communication and synchronization in Go programs. Instead, Go threads more typically communicate by message passing, which is a fundamentally different approach from locks and barriers. The Go mantra for this subject is,
> Do not communicate by sharing memory; instead, share memory by communicating.
That is, _channels_ are used to communicate among goroutines. Values of any type (including other channels!) can be
sent over a channel. Channels can be unbuffered or buffered (using a buffer length specified at channel-construction time).
Channels are first-class values; they can be stored in variables and passed to and from functions like any other value. (When supplied to
functions, channels are passed by reference.) Channels are also typed: a ` chan int ` is different from a ` chan string `.
Because they are so widely used in Go programs, channels are (intended to be) efficient and cheap. To send a value on a channel, use ` <- ` as a binary operator. To receive a value on a channel, use ` <- ` as a unary operator. Channels can be shared among multiple senders and multiple receivers and guarantee that each value sent is received by at most one receiver.
Here is an example of using a manager function to control access to a
single value.
```
type Cmd struct { Get bool; Val int }
func Manager(ch chan Cmd) {
val := 0
for {
c := <-ch
if c.Get { c.Val = val; ch <- c }
else { val = c.Val }
}
}
```
In that example the same channel is used for input and output.
This is incorrect if there are multiple goroutines communicating
with the manager at once: a goroutine waiting for a response
from the manager might receive a request from another goroutine
instead.
A solution is to pass in a channel.
```
type Cmd2 struct { Get bool; Val int; Ch chan<- int }
func Manager2(ch <-chan Cmd2) {
val := 0
for {
c := <-ch
if c.Get { c.Ch <- val }
else { val = c.Val }
}
}
```
To use ` Manager2 `, given a channel to it:
```
func f4(ch chan<- Cmd2) int {
myCh := make(chan int)
c := Cmd2{ true, 0, myCh } // Composite literal syntax.
ch <- c
return <-myCh
}
```

21
GoGetProxyConfig.md Normal file

@ -0,0 +1,21 @@
Setting proxies for source code used by ` go get ` (listed in GoGetTools)
## git
```
$ git config [--global] http.proxy=http://proxy.example.com:port
```
## mercurial
Edit ` ~/.hgrc ` and add the following:
```
[http_proxy]
host=proxy.example.com:port
```
## svn
Edit ` ~/.subversion/servers ` and add the following:
```
[Global]
http-proxy-host=proxy.example.com
http-proxy-port=xxxx
```

10
GoGetTools.md Normal file

@ -0,0 +1,10 @@
# Installing Version Control Tools for ` go get `
The ` go get ` fetching of source code is done by using one of the following tools expected to be found on your system:
* **svn** - Subversion, download at: http://subversion.apache.org/packages.html
* **hg** - Mercurial, download at http://mercurial.selenic.com/wiki/Download
* **git** - Git, download at http://git-scm.com/downloads
* **bzr** - Bazaar, download at http://wiki.bazaar.canonical.com/Download
Refer GoGetProxyConfig for setting proxies for these tools.

59
GoStrings.md Normal file

@ -0,0 +1,59 @@
Strings are **not** required to be UTF-8. Go source code **is** required
to be UTF-8. There is a complex path between the two.
In short, there are three kinds of strings. They are:
1. the substring of the source that lexes into a string literal.
1. a string literal.
1. a value of type string.
Only the first is required to be UTF-8. The second is required to be
written in UTF-8, but its contents are interpreted various ways
and may encode arbitrary bytes. The third can contain any bytes at
all.
Try this on:
```
var s string = "\xFF語"
```
Source substring: ` "\xFF語" `, UTF-8 encoded. The data:
```
22
5c
78
46
46
e8
aa
9e
22
```
String literal: ` \xFF語 ` (between the quotes). The data:
```
5c
78
46
46
e8
aa
9e
```
The string value (unprintable; this is a UTF-8 stream). The data:
```
ff
e8
aa
9e
```
And for record, the characters (code points):
```
<erroneous byte FF, will appear as U+FFFD if you range over the string value>
語 U+8a9e
```

204
GoTalks.md Normal file

@ -0,0 +1,204 @@
# Go talks
Check out http://talks.golang.org for presentations for some of the talks.
# Official
## Introductory Talks
An introduction to Go.
### Russ Cox's Tour of Go
[[video and discussion](http://research.swtch.com/gotour)]
Three things that make Go fast, fun, and productive:interfaces, reflection, and concurrency. Builds a toy web crawler to demonstrate these.
### Go: a simple programming environment
[[video](http://vimeo.com/53221558)]
[[another video](http://vimeo.com/69237265)]
[[slides](http://talks.golang.org/2012/simple.slide)]
Go is a general-purpose language that bridges the gap between efficient statically typed languages and productive dynamic language. But its not just the language that makes Go special Go has broad and consistent standard libraries and powerful but simple tools.
This talk gives an introduction to Go, followed by a tour of some real programs that demonstrate the power, scope, and simplicity of the Go programming environment.
### Get Started with Go
[[video](http://www.youtube.com/watch?v=2KmHtgtEZ1s)]
Get a feel for the language and its standard libraries and tools in thissession, where we go through installing Go and writing some simple but useful
programs.
### Go Programming
[[video](http://www.youtube.com/watch?v=jgVhBThJdXc)] [[code](http://talks.golang.org/2010/io/)]
A presentation delivered by Rob Pike and Russ Cox at Google I/O 2010. It
illustrates how programming in Go differs from other languages through a set of
examples demonstrating features particular to Go. These include concurrency,
embedded types, methods on any type, and program construction using interfaces.
### The Go Tech Talk
[[video](http://www.youtube.com/watch?v=rKnDgT73v8s)]
[[slides](http://talks.golang.org/2009/go_talk-20091030.pdf)]
An hour-long talk delivered by Rob Pike at Google in October 2009.
The language's first public introduction. The language has changed since it was made,
but it's still a good introduction.
## Development in Go
### Writing Web Apps in Go
[[video](http://www.youtube.com/watch?v=-i0hat7pdpk)] [[slides](http://talks.golang.org/2011/Writing_Web_Apps_in_Go.pdf)]
A talk by Rob Pike and Andrew Gerrand presented at Google I/O 2011.
It walks through the construction and deployment of a simple web application
and unveils the [Go runtime for App Engine](http://blog.golang.org/2011/05/go-and-google-app-engine.html).
### Real World Go
[[video](http://www.youtube.com/watch?v=7QDVRowyUQA)] [[slides](http://talks.golang.org/2011/Real_World_Go.pdf)]
A talk by Andrew Gerrand presented at Google I/O Bootcamp 2011.
It gives a broad overview of Go's type system and concurrency model
and provides four examples of Go programs that solve real problems.
### Building Integrated Apps on Google's Cloud Platform
[[video](http://www.youtube.com/watch?v=Mo1YKpIF1PQ)]
A talk by Andrew Gerrand presented at Google Developer Day Japan 2011.
It discusses the development of a web application that runs on Google
App Engine and renders raytraced that it stores on Google Cloud Storage.
### High Performance Apps with Go on App Engine
Google I/O, May 2013
[[video](http://www.youtube.com/watch?v=fc25ihfXhbg)] [[slides](http://talks.golang.org/2013/highperf.slide)]
### Practical Go Programming
[[video](http://www.youtube.com/watch?v=2-pPAvqyluI)] [[slides](http://wh3rd.net/practical-go)] [[code](http://github.com/nf/goto)]
This talk presents the development of a complete web application in Go.
It looks at design, storage, concurrency, and scaling issues in detail, using
the simple example of an URL shortening service.
### Lexical Scanning in Go
[[video](http://www.youtube.com/watch?v=HxaD_trXwRE)]
This GTUG talk by Rob Pike discusses the detailed design of a lexical scanner that uses Go's
features in expressive combinations. (The discussion near the end about avoiding goroutines
at initialization is obsolete: Go 1 allows goroutines in init functions so the extra complexity
is unnecessary.)
### Go in Production
Google I/O, June 2012
[[video](http://www.youtube.com/watch?v=kKQLhGZVN4A)]
Since Go's release in 2009 many companies (besides Google, of course) have used the language to build cool stuff. In this session programmers from several companies will share their first-hand experience using Go in production environments.
### Go: code that grows with grace
[[video](http://vimeo.com/53221560)]
[[slides](http://talks.golang.org/2012/chat.slide)]
One of the Go Programming Languages key design goals is code adaptability; that it should be easy to take a simple design and build upon it in a clean and natural way. In this talk I describe a simple “chat roulette” server that matches pairs of incoming TCP connections, and then use Gos concurrency mechanisms, interfaces, and standard library to extend it with a web interface and other features. Although the function of the program changes dramatically, the inherent flexibility of Go allows the original design to remain intact as it grows.
## Concurrency in Go
### Go concurrency patterns
Google I/O, June 2012
[[video](http://www.youtube.com/watch?v=f6kdp27TYZs)]
### Advanced Concurrency Patterns
[[video](https://www.youtube.com/watch?v=QDDwwePbDtw)]
[[slides](http://talks.golang.org/2013/advconc.slide)]
Google I/0, May 2013
Concurrency is the key to designing high performance network services. This talk expands on last year's popular Go Concurrency Patterns talk to dive deeper into Go's concurrency primitives, and see how tricky concurrency problems can be solved gracefully with simple Go code.
## Design of Go
### The Expressiveness Of Go
[[slides](http://talks.golang.org/2010/ExpressivenessOfGo-2010.pdf)]
A discussion of the qualities that make Go an expressive and comprehensible
language. The talk was presented by Rob Pike at JAOO 2010.
The recording of the event was lost due to a hardware error.
### Another Go at Language Design
[[video](http://sydney.edu.au/engineering/it/videos/seminar_pike) from Sydney University]
[[slides](http://assets.en.oreilly.com/1/event/45/Another%20Go%20at%20Language%20Design%20Presentation.pdf)]
A tour, with some background, of the major features of Go, intended for
an audience new to the language. The talk was presented at OSCON 2010.
This talk was also delivered at Sydney University in September 2010.
### Go Emerging Languages Conference Talk
[[slides](http://assets.en.oreilly.com/1/event/45/Go%20Presentation.pdf)] [[video](http://confreaks.com/videos/115-elcamp2010-go)]
Rob Pike's Emerging Languages Conference presentation delivered in July 2010. Talk abstract:
> Gos approach to concurrency differs from that of many languages, even those
> (such as Erlang) that make concurrency central, yet it has deep roots. The path
> from Hoares 1978 paper to Go provides insight into how and why Go works as it
> does.
## Miscellaneous
### The Go frontend for GCC
[[paper](http://talks.golang.org/2010/gofrontend-gcc-summit-2010.pdf)]
A description of the Go language frontend for gcc.
Ian Lance Taylor's paper delivered at the GCC Summit 2010.
### The Go Promo Video
[[video](http://www.youtube.com/watch?v=wwoWei-GAPo)]
A short promotional video featuring Russ Cox demonstrating Go's fast compiler.
### Meet the Go team
Google I/O, June 2012
[[video](http://www.youtube.com/watch?v=sln-gJaURzk)]
A panel discussion with David Symonds, Robert Griesemer, Rob Pike, Ken Thompson, Andrew Gerrand, and Brad Fitzpatrick.
### Fireside Chat with Go team
Google I/0, May 2013
[[video](http://www.youtube.com/watch?v=p9VUCp98ay4)]
A fireside chat with Andrew Gerrand, Brad Fitzpatrick, David Symonds, Ian Lance Taylor, Nigel Tao, Rob Pike, Robert Griesemer, Sameer Ajmani.
# Unofficial
Talks by members of the community.
### Let's Go, or introduction to Go
[[video (starting at 14:35)](http://live.digicast.ru/view/1582)] [[slides](http://talks.godoc.org/github.com/AlekSi/LetsGo/lets-go.slide)] [[source](https://github.com/AlekSi/LetsGo)]
This talk gives an introduction to Go in Russian.

80
GoUserGroups.md Normal file

@ -0,0 +1,80 @@
### Contributing
To edit this page you must be a contributor to the go-wiki project. To get contributor access, send mail to [adg@golang.org](mailto:adg@golang.org) from your Google Account.
Is your area not listed below? Check out [this list](http://golang.meetup.com/all/) of people from around the world that are interested in Go meetups.
# Africa
* [Go Cape Town User Group](http://www.meetup.com/Go-Cape-Town-User-Group) - Cape Town.
* [golang-dakar](https://plus.google.com/u/0/communities/116552609416802012105) Dakar (Sénégal)
# Asia
* [golang-china](http://groups.google.com/group/golang-china) - China.
* [Golang JP](https://plus.google.com/communities/107075098212007233819) - Japan.
* [GDG Korea Golang](https://plus.google.com/u/0/communities/115721275599816202991) - Korea.
* [Golang VN](https://plus.google.com/communities/104475612935018972341) - Vietnam
* [Golang Taiwan](http://golang.tw) - Taiwan.
* [Golang India](https://plus.google.com/communities/102083447604771785504) - Bangalore, India.
* [Golang Pune](https://plus.google.com/communities/103673348666338246281) - Pune, India.
* [Golang Israel](http://www.meetup.com/Go-Israel) - Israel.
# Europe
* [Amsterdam, NL](http://www.meetup.com/golang-amsterdam/)
* [golang-users-berlin](http://www.meetup.com/golang-users-berlin/) - Berlin, Germany.
* [Got-go](http://www.meetup.com/Got-go/) - Gothenburg, Sweden.
* [Go-User-Group-Hamburg](http://www.meetup.com/Go-User-Group-Hamburg) - Hamburg, Germany.
* [Go London User Group](http://www.meetup.com/Go-London-User-Group/) - London, UK.
* [Golang Москва](http://www.meetup.com/Golang-Moscow/) - Moscow, Russia.
* [Golang Питер](http://www.meetup.com/Golang-Peter/) - Saint Petersburg, Russia.
* [Munich Gophers](http://www.meetup.com/Munich-Gophers-Go-User-Group/) - Munich, Germany
* [Golang Paris](http://www.meetup.com/Golang-Paris) - Paris, France.
* [golang-pl](https://groups.google.com/forum/?fromgroups#!forum/golang-pl) - Poland.
* [Golang Warsaw](http://www.meetup.com/Golang-Warsaw) - Warsaw, Poland.
* [Go-Stockholm](http://www.meetup.com/Go-Stockholm/) - Stockholm, Sweden.
* [GolangIT](http://golangit.github.io/) - Italy.
* [Go-Turkey](https://plus.google.com/communities/101920753066440157216) - Turkey.
* [Go Graz](https://plus.google.com/communities/106198408392520934164) - Graz, Austria
* [Meetup Lausanne](http://www.meetup.com/Lausanne-golang-Meetup) - Lausanne, Switzerland
* [Meetup Zurich](http://www.meetup.com/Zurich-Gophers/) - Zurich, Switzerland
* [Meetup Frankfurt](http://www.meetup.com/Frankfurt-Gophers-Meetup/) - Frankfurt am Main, Germany
# North America
* [Edmonton Go Meetup](http://edmontongo.org/) - Edmonton AB, Canada.
* [vangophers](http://groups.google.com/group/vangophers) - Vancouver BC, Canada.
* [Go Vancouver](https://plus.google.com/u/0/communities/106063002572645508555) - Vancouver BC, Canada.
* [GoTO](http://www.meetup.com/go-toronto) - Toronto ON, Canada.
* [golangmx](http://golang.mx/) - Mexico City, Mexico.
* [Los-Angeles-Gophers](http://www.meetup.com/Los-Angeles-Gophers/) - Los Angeles CA, USA.
* [Golang Mountain View](http://www.meetup.com/Golang-Mountain-View/) - Mountain View CA, USA.
* [OC Gophers](http://www.meetup.com/Orange-County-Gophers) - Orange County CA, USA.
* [GoSF](http://www.meetup.com/golangsf/) - San Francisco CA, USA.
* [GoSV](http://www.meetup.com/GolangSV/) - San Mateo CA, USA.
* [Denver Go Language User Group](http://www.meetup.com/Denver-Go-Language-User-Group/) - Denver CO, USA.
* [Go-Miami](http://www.meetup.com/Go-Miami/) - Miami FL, USA.
* [Go-Users-Group-Atlanta](http://www.meetup.com/Go-Users-Group-Atlanta/) - Atlanta GA, USA.
* [chicagolang](http://groups.google.com/group/chicagolang) - Chicago IL, USA.
* [Go Boston](https://plus.google.com/u/0/communities/103337146295481792015) - Boston MA, USA.
* [GoMN](http://www.meetup.com/golangmn/) - Minneapolis MN, USA.
* [Davidson Golang](http://www.meetup.com/Davidson-Golang/events/167980892/) - Davidson NC, USA.
* [New York Go Language Meetup](http://www.meetup.com/golangny/) - New York NY, USA.
* [GoPDX](http://groups.google.com/group/go-pdx) - Portland OR, USA.
* [GoLangPhilly](http://www.meetup.com/GoLangPhilly/) - Philadelphia PA, USA.
* [Go Steel Programmers](http://meetup.go-steel-programmers.org/) - Pittsburgh PA, USA.
* [ATX-Golang](http://www.meetup.com/atxgolang/) - Austin TX, USA.
* [GoDFW](http://www.meetup.com/GoCowboys/) - Dallas TX, USA.
* [Utah Gophers](http://www.meetup.com/utahgophers/) - Salt Lake City UT, USA.
* [Golang-DC](http://www.meetup.com/Golang-DC/) - Arglinton VA, USA.
# Oceania
* [golang-sydney](http://www.meetup.com/golang-syd/) - Sydney, Australia.
* [golang-nz](http://groups.google.com/group/golang-nz) - New Zealand.
* [Melbourne-Go-Nuts](http://www.meetup.com/Melbourne-Go-Nuts) - Melbourne, Australia.
* https://plus.google.com/u/1/communities/114036877112593565975 - Canberra, Australia.
# South America
* [Golang Brasil](http://www.golangbr.org) - Brazil.

113
GoUsers.md Normal file

@ -0,0 +1,113 @@
# Currently using Go
* [Google](http://google.com/) - the core Go team work at Google. Most uses of Go at Google are confidential. The [YouTube](http://youtube.com/) team have released their [MySQL scaling infrastructure](http://code.google.com/p/vitess/) as open source software. And dl.google.com is written in Go: [mailing list discussion](https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/BNUNbKSypE0) / [OSCON slides](http://talks.golang.org/2013/oscon-dl.slide#1). Other known uses include the [Turkey Doodle (2011)](http://blog.golang.org/2011/12/from-zero-to-go-launching-on-google.html), the [Santa Tracker (2012)](https://www.youtube.com/watch?v=fc25ihfXhbg), [writing map/reduce jobs](http://simplystatistics.org/2013/02/15/interview-with-nick-chamandy-statistician-at-google/), [Jam With Chrome](http://www.jamwithchrome.com/technology), the [CubeSlam Chrome Experiment](https://code.google.com/p/cubeslam/), and the [pprof command line tool](https://codereview.appspot.com/153750043/).
* [10gen](http://www.10gen.com) - [blog](http://blog.mongodb.org/post/51643994762/go-agent-go)
* [6Wunderkinder](http://www.6wunderkinder.com/) - [video](https://www.youtube.com/watch?v=sVpMc0hwqps)
* [99designs](http://www.99designs.com) - [golang-nuts](https://groups.google.com/d/msg/golang-nuts/eeAmkzaRt-w/rmxBZszJUCcJ)
* [ActiveState](http://www.activestate.com) - [github](https://github.com/activestate)
* [adeven](http://www.adeven.com) - [blog](http://big-elephants.com/2012-10/deploying-go-with-capistrano/) [github](https://github.com/adeven)
* [Airbrake](http://airbrake.io/) - [blog](http://blog.airbrake.io/status/planned-airbrake-migration-love-go-love-riak/)
* [Apcera ](http://www.apcera.com) - [blog](http://gigaom.com/2012/09/13/will-go-be-the-new-go-to-programming-language/)
* [Aruba Networks](http://www.arubanetworks.com/) - [golang-nuts](https://groups.google.com/d/msg/golang-nuts/M2koiSyoF6E/8rUujT5RCwEJ)
* [BBC Worldwide](http://www.bbcworldwide.com/) - [source](http://www.quora.com/Go-programming-language/Is-Google-Go-ready-for-production-use/answer/Kunal-Anand)
* [Beachfront Media](http://www.beachfrontmedia.com) [article](http://arstechnica.com/information-technology/2013/05/my-favorite-programming-language-googles-go-has-some-coders-raving/)
* [Betable](https://betable.com) - [talk #1](http://rcrowley.org/talks/surge-2013.html), [talk #2](http://rcrowley.org/talks/strange-loop-2013.html)
* [Bitbucket](https://bitbucket.org/) - [source](http://www.reddit.com/r/golang/comments/1pjn0k/bitbucket_hiccup_reveals_go_usage/)
* [bitly](http://bit.ly) - [github](https://github.com/bitly/nsq) [blog](http://word.bitly.com/post/33232969144/nsq)
* [Canonical](http://canonical.com/) - [source](http://www.youtube.com/watch?v=7QDVRowyUQA)
* [Carbon Games](http://carbongames.com/) - [source](http://carbongames.com/opensource.html#the_go_programming_language_bsd)
* [CloudFlare](http://www.cloudflare.com/) - [blog](http://blog.cloudflare.com/go-at-cloudflare) [article](http://arstechnica.com/information-technology/2013/02/cloudflare-blows-hole-in-laws-of-web-physics-with-go-and-railgun/)
* [Cloud Foundry](http://www.cloudfoundry.com) - [blog](http://pivotallabs.com/a-rubyist-learning-go-a-basic-go-program/) [github](https://github.com/cloudfoundry)
* [CloudWalk](https://www.cloudwalk.io) - [github](https://github.com/cloudwalkio/)
* [clypd](http://www.clypd.com) - [blog](http://www.clypd.com/getting-to-go/)
* [Conformal Systems](http://www.conformal.com) - [blog post](https://blog.cyphertite.com/go-at-conformal/) [github](https://github.com/conformal)
* [Crashlytics](http://try.crashlytics.com/) - [tweet](https://twitter.com/brianhatfield/status/360866306276327424)
* [Cupcake](https://cupcake.io) - [tweet](https://jonathan.cupcake.is/posts/QweOXcW6rmbdj16aXlEdNA) [github](https://github.com/cupcake)
* [CustomerIO](http://www.customer.io) - [tweet](https://twitter.com/jrallison/status/365560974251540481)
* [Digital Ocean](http://www.digitalocean.com/) - [blog](http://www.digitalocean.com/company/blog/get-your-development-team-started-with-go/)
* [Disqus](http://disqus.com/) - [blog](http://blog.disqus.com/post/51155103801/trying-out-this-go-thing)
* [DNSimple](https://dnsimple.com/) - [blog](http://blog.dnsimple.com/a-golang-redirection-service/)
* [domainr](http://domai.nr/) - [tweet](https://twitter.com/rr/status/368988340848037889)
* [dotCloud](http://www.dotcloud.com) - [docker](http://docker.io/) [slides](http://www.slideshare.net/jpetazzo/docker-and-go-why-did-we-decide-to-write-docker-in-go)
* [drone.io](http://drone.io) - [post](https://groups.google.com/d/msg/golang-nuts/Lo7KP3rWP3o/GvNju75FgPIJ) [github](https://github.com/drone)
* [Dropbox](http://www.dropbox.com) - [blog](https://tech.dropbox.com/2014/07/open-sourcing-our-go-libraries/), [github](https://github.com/dropbox/godropbox)
* [Embedly](http://embed.ly) - [blog](http://blog.embed.ly/post/45149878472/167857590)
* [ErrPlane](http://www.errplane.com) - [blog](http://techcrunch.com/2013/03/18/errplane-performance-monitoring-and-alert-service-for-web-apps/)
* [Foize](https://www.foize.com) - [github](https://github.com/foize/)
* [Flipboard](http://www.flipboard.com) - [source (job post)](https://news.ycombinator.com/item?id=6140956)
* [Getty Images](http://www.gettyimages.com) - [tweet](https://twitter.com/TrevorBramble/status/441372661336113152) [tweet](https://twitter.com/ickypop/status/441470245492908032)
* [GitHub](https://github.com) - [blog post](http://techno-weenie.net/2013/11/2/key-value-logs-in-go/)
* [Globo.com](http://www.globo.com) - [github](https://github.com/globocom) [article](http://www.wired.com/wiredenterprise/2013/03/tsuru/)
* [GOV.UK](http://www.gov.uk) - [slides](https://speakerdeck.com/nickstenning/http-building-a-new-router-for-gov-dot-uk) [github](https://github.com/alphagov/router) [blog](https://gdstechnology.blog.gov.uk/2013/12/05/building-a-new-router-for-gov-uk/)
* [Granify](http://granify.com/) - [blog](http://leonsbox.com/blog/2013/06/04/improving-testing-by-using-real-traffic-from-production/)
* [Hailo](http://www.hailocab.com) - [slides](https://speakerdeck.com/mattheath/youre-good-to-go)
* [Heroku](http://heroku.com/) - [Go blog post](http://blog.golang.org/2011/04/go-at-heroku.html)
* [Intel Germany (Debugger QA Team)](http://www.intel.com) - [source](http://www.reddit.com/r/golang/comments/16qw6x/the_intel_debugger_qa_team_in_germany_ulm_is/)
* [Iron.io](http://iron.io/) - [source](http://www.youtube.com/watch?v=kKQLhGZVN4A) [blog:"30 servers to 2"](http://blog.iron.io/2013/03/how-we-went-from-30-servers-to-2-go.html) [blog:"2 years of production Go"](http://blog.iron.io/2013/08/go-after-2-years-in-production.html)
* [JelloLabs](http://www.jellolabs.com) - [blog](http://www.jellolabs.com/blog/why-golang-is-ready-for-early-stage-startups.html)
* [Jimdo](http://www.jimdo.com) - [tweet](https://twitter.com/mlafeldt/status/351661314017476608) [github](https://github.com/jimdo)
* [Koding](http://www.koding.com) - [quora](http://www.quora.com/Node-js/Why-did-Koding-switch-from-Node-js-to-Go)
* [Lincoln Loop](http://lincolnloop.com/) - [blog (as part of https://botbot.me/ , #go-nuts IRC logging)](http://lincolnloop.com/blog/djangonaut-building-webapp-go-gorilla/)
* [New Bamboo](http://www.new-bamboo.co.uk) - [blog](http://blog.new-bamboo.co.uk/2013/09/17/micro-network-daemons-in-go)
* [MaxCDN](http://www.maxcdn.com) - [blog](http://blog.maxcdn.com/learned-stop-worrying-love-logs/)
* [Microcosm](http://www.microco.sm) - [slides](https://speakerdeck.com/mattcottingham/building-an-api-with-go-at-microco-dot-sm)
* [Modcloth](http://www.modcloth.com) - [github](https://github.com/modcloth-labs)
* [Moovweb](http://www.moovweb.com) - [github](https://github.com/moovweb) [source](https://groups.google.com/forum/#!topic/golang-nuts/MeiTNnGhLg8/discussion)
* [Mozilla Services](https://github.com/mozilla-services) - [github](https://github.com/mozilla-services/heka) [blog](https://blog.mozilla.org/services/2013/04/30/introducing-heka/)
* [MROffice](http://mroffice.org/) - [source](http://www.youtube.com/watch?v=7QDVRowyUQA)
* [New York Times](http://nyt.com/) - [source](http://open.blogs.nytimes.com/2014/07/10/emr-streaming-in-go/?_php=true&_type=blogs&_r=0)
* [ngmoco:)](http://ngmoco.com/) - [blog](http://ngenuity.ngmoco.com/2012/01/introducing-falcore-and-timber.html)
* [Novartis](http://www.novartis.com) - [g+ post](https://plus.google.com/114945221884326152379/posts/d1SVaqkRyTL)
* [Ooyala](http://www.ooyala.com/) - [github](https://github.com/ooyala/)
* [Oyster Books](https://www.oysterbooks.com/) - [blog](http://engineering.oysterbooks.com/post/79458380259/resizing-images-on-the-fly-with-go)
* [Percona](http://www.percona.com) - [blog](http://www.mysqlperformanceblog.com/2014/05/14/tips-benchmarking-go-mysql/)
* [Plano Bê](https://www.planobe.com.br) - [podcast](http://www.grokpodcast.com/2013/07/17/episodio-95-golang/)
* [pool.ntp.org](http://pool.ntp.org/) - [blog](http://news.ntppool.org/2012/10/new-dns-server.html) [status](http://dns-status.ntppool.org/)
* [Poptip](https://poptip.com/) [job posting](https://groups.google.com/d/msg/golang-nuts/cQ0uuLCcQQQ/4nNm_YYh_l4J)
* [Rawstream ](http://www.rawstream.com) - [tweets](https://twitter.com/brianazzopardi/status/387920069327872000)
* [Raygun](http://raygun.io) - [blog](http://raygun.io/blog/2013/11/5-reasons-go-will-kick-ass-in-your-next-project/)
* [Rendered :Text](http://renderedtext.com/) - [blog](http://renderedtext.com/blog/2013/08/28/building-our-first-app-in-go/)
* [Repustate](http://www.repustate.com) - [blog](http://blog.repustate.com/migrating-code-from-python-to-golang-what-you-need-to-know/2013/04/23/)
* [Rounds](http://www.rounds.com) - [blog](http://www.rounds.com/blog/joys-affordable-concurrency/)
* [Secret](https://www.secret.ly/) - [blog](https://medium.com/secret-den/12ab82fda29f)
* [SendGrid](http://sendgrid.com/) - [blog](http://sendgrid.com/blog/convince-company-go-golang/)
* [SendHub](https://www.sendhub.com/) - [source (shipbuilder PaaS)](http://shipbuilder.io/)
* [Shopify](http://www.shopify.com) [tweet](https://twitter.com/burkelibbey/status/312328030670450688)
* [Showyou](http://www.showyou.com) [source](https://plus.google.com/101522949595361604155/posts/8n4CSePMwgV)
* [SmartyStreets](http://smartystreets.com) [source](http://mwholt.com/autocomplete#technical)
* [SmugMug](http://www.smugmug.com/) - [blog](http://sorcery.smugmug.com/2012/04/06/deriving-json-types-in-go/)
* [Skimlinks](http://www.skimlinks.com) [blog](https://speakerdeck.com/rjohnsondev/go-at-skimlinks)
* [SoundCloud](http://soundcloud.com) - [blog](http://backstage.soundcloud.com/2012/07/go-at-soundcloud/)
* [Sourcegraph](https://sourcegraph.com) [github](https://github.com/sourcegraph)
* [Space Monkey](http://www.spacemonkey.com) - [blog](https://www.spacemonkey.com/blog/posts/go-space-monkey)
* [Splice](http://splice.com) - [tweet](https://twitter.com/mattetti/status/387935640513683456)
* [Square](http://www.squareup.com) - [blog](http://corner.squareup.com/2014/05/evaluating-go-frameworks.html)
* [StatHat](http://stathat.com/) - [Go blog post](http://blog.golang.org/2011/12/building-stathat-with-go.html)
* [Steals.com](http://steals.com) [blog](http://blog.gopheracademy.com/day-15-shopping-with-go)
* [Streetspotr](http://streetspotr.com) - [tweet](https://twitter.com/thcyron/status/372350650580865024)
* [Stretchr](http://stretchr.com/) [github](https://github.com/stretchrcom)
* [SyndicatePro](http://syndicatepro.com/) - [source](https://groups.google.com/d/msg/golang-nuts/eeAmkzaRt-w/rHpoRAGeLD8J)
* [Tamber](http://www.tamber.com/) - [blog](http://www.tamber.com/posts/ferret.html)
* [The Plant](http://theplant.jp) - Developing [Qortex](http://qortex.com), a social productivity application, and backend infrastructure using Go. [source](http://theplant.jp/en/about)
* [Thomson Reuters Eikon](https://github.com/ThomsonReutersEikon) - [github](https://github.com/ThomsonReutersEikon) [source](https://groups.google.com/forum/?fromgroups#!topic/golang-nuts/ikt3hcIqicA)
* [Thumbtack](http://thumbtack.com) - [Go Hercule blog post](http://www.thumbtack.com/engineering/go-hercule/)
* [TinkerCad](http://tinkercad.com/)
* [Toggl](http://www.toggl.com) - [blog](http://blog.toggl.com/2012/09/moving-to-go/)
* [Torbit ](http://www.torbit.com) - [blog](http://torbit.com/blog/2013/02/19/big-data-at-torbit/)
* [Tumblr ](http://www.tumblr.com) - [github](https://github.com/tumblr/gocircuit) [source](https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/qelU5Lrq-uA)
* [Twitch](http://www.twitch.tv/) - [blog](http://blog.twitch.tv/2014/04/technically-speaking-group-chat-and-general-chat-engineering/)
* [TweetQureet](http://qureet.com) - [blog](http://www.qureet.com/blog/golang-technology-stack/)
* [Undisclosed.ch](https://undisclosed.ch/) - [github](https://github.com/xoba/goutil)
* [Urlist](http://urli.st/) - [tweet](https://twitter.com/ScintillaLuz/status/364767411750174720)
* [Viki](http://www.viki.com/) - [github](https://github.com/viki-org/)
* [VividCortex](https://vividcortex.com/) - [source](https://vividcortex.com/jobs/) [github](https://github.com/VividCortex/)
* [Zynga](http://www.zynga.com) - [source (zbase component)](http://code.zynga.com/2013/08/zbase-a-high-performance-elastic-distributed-key-value-store/) [github](https://github.com/zbase)
# Tried Go, but moved away
* [Atlassian](http://atlassian.com/) - [using](http://www.youtube.com/watch?v=7QDVRowyUQA) [not using](http://news.ycombinator.com/item?id=4159654), but [bitbucket is experimenting with Go again](https://twitter.com/nperson/status/395553183201628160/photo/1)
* [Braintree Payments](http://braintreepayments.com) - [blog](https://www.braintreepayments.com/braintrust/gotchas-irritants-and-warts-in-go-web-development)
Also: [Organizations using Go](http://go-lang.cat-v.org/organizations-using-go) and [SuccessStories](wiki/SuccessStories)

41
GoVsGenerics.md Normal file

@ -0,0 +1,41 @@
# Introduction
This is page tries to enumerate the Use Cases that call for generics and give a Go alternative without using generics.
Who knows, you might find you really didn't need generics for that at all!
# Details
**FIRST USE CASE: Generic Algorithm on data whose Type you Don't Yet Know**
...but needs to follow some Properties or Behaviours...
You just use interfaces to define the properties or behaviours your data needs to be able to be used by your Generic Algorithm. As exemplified by the sort package:
http://golang.org/pkg/sort/#Interface
# Unresolved USE CASES
- map() in Python: **map(lambda x:x\*2, range(100))**:
```
func Map(f interface{}, v interface{}) interface{} {
// Reflection to solve f and v types
}
```
The reflect solution performance is really bad
- Polymorphic functions that operate on built-in generic types.
```
func KeyIntersection(a map[T1]T2, b map[T1]T2) map[T1]T2 {}
```
- Containers that must store non-interface values. (Various
motivations: control memory layout, require an immutable copy...)
# Under construction...
This page is under construction.
It feeds from a discussion thread on golang nuts:
http://groups.google.com/group/golang-nuts/browse_thread/thread/3d825ac84e742598

35
HandlingIssues.md Normal file

@ -0,0 +1,35 @@
This document explains how we handle issue triage and scheduling in [the Go project's issue tracker](http://golang.org/issue).
# New issues
All new issues are created with status "New" and no other labels.
When an issue is changed from "New" to "Accepted" (or any open state):
* Mark it with a Release-**label (see below).
* Add a sentence that describes the rationale for the label.**
If you're a committer creating an issue, you can change it from “New” to “Accepted” while filing the issue, but if you do, be sure to add a Release-**label and a rationale.**
# Release Labels
Any issue planned for a specific release (or explicitly not planned for a release) must have one of these labels:
* Release-Go1.3 - must be addressed (and probably fixed) for Go 1.3
* Release-Go1.3Maybe - would be nice if it were addressed for Go 1.3
* Release-Go1.4 - will be re-examined for the next release
* Release-None - no plan to fix in any specific release
# Dashboards
* [Status-New](http://research.swtch.com/dashboard/Status-New)
* [Release-Go1.3](http://research.swtch.com/dashboard/Go1.3)
* [Release-Go1.4](http://research.swtch.com/dashboard/Go1.4)
* [Release-None](http://research.swtch.com/dashboard/Release-None)
# Nominating an issue
If you're not a committer and you would like an issue to be addressed in Go 1.3, please:
* Leave a comment on the issue explaining why,
* Include the hashtag "#go13" in the comment.
Committers were periodically look at the issues with #go13 comments and adjust their status accordingly.

25
Hashing.md Normal file

@ -0,0 +1,25 @@
Please consider move this into document for package ` hash `.
# Hashing
## The hash.Hash interface
All hashes defined in the standard library implement the hash.Hash interface. The Hash interface allows you to input data, get the sum (hash) of the previously inputted data, and forget previously inputted data. It also has some methods which return constants based on the hash type.
To input data, you use the Write method. For example:
```
h.Write(byteSlice)
```
or
```
io.Copy(h, file)
```
While Write returns an int and error, these are just to comply with the io.Writer interface. A hash will never return an error or an n != len(byteSlice).
At any time during data input, you can get the current sum by calling the Sum method. Use of the Sum() method will not effect future calls to sum. The most common way to use it is sum := h.Sum(nil). What the Sum() method does is append the sum to the [wiki/](wiki/)byte parameter and return the new [wiki/](wiki/)byte. This can allow you to avoid allocating a new [wiki/](wiki/)byte each time you want the Sum. If you are summing often, you may do md5sum := make([wiki/](wiki/)byte, 16) once and then do h.Sum(md5sum[:0]) each time you want the new hash.
If you want to reuse an already created hash, you can use Reset() to ensure it forgets all previously inputted data.

@ -0,0 +1,17 @@
# Introduction
A number of hosted continuous integration platforms have support for Go
# Details
| Provider | Documentation | Notes |
|:---------|:--------------|:------|
| [AppVeyor](http://www.appveyor.com/) | https://bitbucket.org/appveyor/test-go | Windows |
| [CircleCI](https://circleci.com/) | | |
| [Codeship](http://codeship.io) | https://www.codeship.io/documentation/languages-and-frameworks/go/ | |
| [drone.io](http://drone.io/) | http://docs.drone.io/golang.html | open-source version: https://github.com/drone/drone |
| [GoCI](http://goci.me/) | http://goci.me/how | source code: https://github.com/zeebo/goci |
| [Magnum CI](https://magnum-ci.com/) | https://magnum-ci.com/docs/go | |
| [Travis CI](http://travis-ci.org) | http://docs.travis-ci.com/user/languages/go/ | |
| [Wercker](http://wercker.com/) | http://blog.wercker.com/2013/07/10/Golang-on-wercker.html | |

114
HowToAsk.md Normal file

@ -0,0 +1,114 @@
# A quick introduction
Imagine you want to know how to get from "Old street" to "New street". You call a random person to get help and you ask "What is the fastest way I can get from Old street 19 to New street 3?". Would the random person be able to help you?
There are a lot of "New" and "Old" streets in the world, so first he would need to know what country and city you are in. If the street layout is complicated then maybe you need to name some buildings that are near you. Of course because speed is an issue then your means of transportation is also important; are you by foot, bike, car or truck? You can go on foot into places where you can't get by truck.
Those questions around the immediate question "How do I X?" is the context of the problem, it helps other people orient to the problem. Giving advice without context could mean that the other person will describe the wrong city.
In person it's easy to ask those questions and can be done in rapid succession, although on the forums this will result in a lot of back-and-forth questions that can be avoided. So, how to properly give the context to the problem?
# How to ask a good question
People on the forums have limited time available. So, to speed things up, here is a small template for asking a question that will get better answers and answers quicker:
> The gist of the problem you are having.<br>
<blockquote><br>
How did you encounter the problem?<br>
What are you trying to accomplish?<br>
What is the context of the problem?<br>
What are the requirements for the solution?<br>
What are the context-specific constraints/properties?<br>
Your compilable and runnable example on <a href='http://play.golang.org'>play.golang.org</a><br>
<br>
Other notes about the situation (production/school/playing/learning)</blockquote>
Things to keep in mind:<br>
<ul><li>Take your time to spell-check and make sure that your sentences are readable.<br>
</li><li>The solution can be far away from the immediate problem. So be sure that the question contains answers to the <a href='http://en.wikipedia.org/wiki/5_Whys'>5 whys</a>. The template implicitly already contains answers to 3 whys.<br>
</li><li>The context of the question is important, so always give one. Not giving the context may end up hurting you, because youll get an answer thats more suited to a different context. The context is the end-user or domain problem and goal, with the information how it tries to solve it.<br>
</li><li>Try not to ask abstract questions but if you do then add multiple concrete examples. Asking abstract things without concrete examples (usually) wastes time. Although they can be sometimes interesting, the concrete examples allow the discussion to be precise.<br>
</li><li>Avoid imprecise terms such as "a lot of data" or "needs to work fast". Give something measurable such as "it needs to work upto 1GB of data" or "it needs to communicate with 1000 concurrent clients within 100ms".<br>
</li><li>If you are not able to give the compilable example in go, any language will do... many people are well versed in other languages. If you are not able to make it compile or run, it's fine too.<br>
</li><li>Try to explain your situation:<br>
<ul><li>Noting that "it is homework" means people can explain a bit more and won't do the homework for you.<br>
</li><li>Information such as "it needs to work on a cluster of X nodes" can provide situational context. Where and how the code must eventually run.<br>
</li><li>Noting that "its for learning X" makes it clear that you are trying to get a deeper understanding of different approaches.<br>
</li><li>Noting that "Im under NDA and cant disclose the code", means people wont bother asking for it. Although you should still try to come up with a similar situation, it helps the answerer.<br>
</li></ul></li><li>Giving a simplified example can be helpful for readers, but do not forget to give the full version as well. The simplified version is different from the full version and therefore the solutions can be different.</li></ul>
Of course, don't worry too much... you can't answer all possible questions. It's not needed to write a 4 page essay on the whole thing. People can always ask when something needs clarification.<br>
<br>
<h1>The story of a bad question</h1>
Why is that template necessary? Let's put you in the shoes of the answerer, and let's say you get this question:<br>
<br>
<blockquote>How do I use the reflect <code>Set</code> method?</blockquote>
From the askers perspective this may look like a straightforward problem. Of course, you have no idea what the asker is trying to do. Is he trying to set a value on a value, struct, array or a map? This means you need to ask the first question: <i>Can you give an example?</i>.<br>
<br>
Now the asker will provide an example:<br>
<br>
<blockquote>I'm basically trying to do this:<br>
<pre><code> m := make(map[string]int)<br>
v := reflect.ValueOf(m)<br>
key := reflect.ValueOf("hello")<br>
val := reflect.ValueOf(123)<br>
v.MapIndex(k).Set(val)<br>
print(m)<br>
</code></pre>
But it just panics.</blockquote>
Now you've got some code that even doesn't compile. This means you need to copy paste it somewhere and fix the mistakes. Putting it on <a href='http://play.golang.org'>play.golang.org</a> makes it easier to see the problem (e.g. <a href='http://play.golang.org/p/fCxBlL9V4Y'>play.golang.org/p/fCxBlL9V4Y</a>).<br>
<br>
<i>The fix is simple; just use <code>SetMapIndex</code> instead.</i> Of course that may not be the full story. The asker now comes back with another problem:<br>
<br>
<blockquote>Yay, I've got the reflection working, but it's not fast enough.<br>
How can I make it faster?</blockquote>
What does "faster" mean? What is he trying to do? So you need to ask more about the specifics of the problem. So you ask: <i>What are you trying to accomplish?</i>
<blockquote>I'm trying to implement a set package that can store generic types.</blockquote>
Well, ok, but that still didn't answer why it needs to be faster. Why is he using <code>reflect</code> for that anyway, when you can use <code>map</code> instead. So you answer: <i>Can't you just use <code>map</code> instead (e.g. <code>map[type]struct{}</code>)? What are you writing the <code>set</code> package for?.</i>
<blockquote>I'm writing a program that goes over multiple sequences and that finds the common elements.<br>
The main use for is for using on nucleotides and it should work on large datasets. But it should also work on proteins, which are represented by another type.</blockquote>
<blockquote>Yes, the <code>map[NucleotideIndex]struct{}</code> works a bit better, but it's still not fast enough, and I would now have to write the same code for proteins.</blockquote>
Finally we have all the information that's needed. The solution is straightforward: <i><code>biogo</code> <a href='https://code.google.com/p/biogo/'>https://code.google.com/p/biogo/</a> has most of the stuff necessary for handling large datasets and parallelism etc. Also what's the "<code>NucleotideIndex</code>".</i> The asker may have found the answer and say: <i>Thanks that's really nice.</i> but there is a possibility of:<br>
<br>
<blockquote>Whoa, that looks nice, but I'm in a bioinformatics course and we need to write that code ourselves. The "<code>NucleotideIndex</code>" is a "<code>struct {Nucleotide Nucleotide; Index int}</code>".</blockquote>
That looks weird, why would you do it that way. Nevertheless we've all done something stupid, so... now you can start suggesting something better: <i>Probably dealing with <code>map[Type]map[int]struct{}</code> would be much easier. Because you are dealing with sequences and the set elements are always used in an increasing order you can just store the index in an array e.g. <code>map[Type][]int</code>. Also if the memory starts to become the problem you could make it into a run-length-encoded set...</i>
Now we can have a more meaningful discussion about the (dis)advantages of different set types.<br>
<br>
Hopefully after this long example, you probably understand why it's useful to provide more information. The initial back and forth questions could have been avoided. Proper question could have saved time for the question asker and the answerer.<br>
<br>
The initial question could have been:<br>
<br>
<blockquote>How do I use the reflect <code>Set</code> method with <code>MapIndex</code>?<br>
<br>
I'm trying to set a value on a generic map for a set package. But it just gives a panic when I try to do that. <a href='http://play.golang.org/p/fCxBlL9V4Y'>play.golang.org/p/fCxBlL9V4Y</a><br>
<br>
I use the set package in a program that goes over multiple sequences and find all the common elements in a sequence. The sequence elements could be nucleotides or proteins. The program needs to be able to deal with data-sizes upto 1GB.<br>
<br>
My current code is available at github.com/... <br>
<br>
I'm writing this for a bioinformatics course, so I need to implement it myself.</blockquote>
Summary:<br>
<br>
<ul><li>The best answer depends on the context. In some cases maybe <a href='http://research.swtch.com/sparse'>research.swtch.com/sparse</a> would be more appropriate. If the speed isn't important using a <code>map</code> would be sufficient. So the requirements are also important.<br>
</li><li>The problem can be somewhere else. As you saw the answerer didn't expect that the structure of the program was at fault. Using a struct <code>NucleotideIndex</code> with a <code>map</code>, meant he had to build elaborate things with reflection. Often when you fix the higher-level problem, everything else will become much easier.<br>
</li><li>Constraints/properties matter. The property "set elements are used in increasing order" meant that there was a simple method that didn't require a full-blown <code>set</code> implementation. This specialized structure can be much faster. The information about the system, context or domain may make the problem much simpler.<br>
</li><li>The solution may differ from your usual approaches. Maybe the asker decided to use <code>reflect</code> package, because he was used to generics in Java. Go is different language, so the final solution may look a lot different from the solution in Java.</li></ul>
<h1>More tips</h1>
<ul><li><a href='http://stackoverflow.com/help/how-to-ask'>How to ask</a>
</li><li><a href='http://msmvps.com/blogs/jon_skeet/archive/2010/08/29/writing-the-perfect-question.aspx'>Writing the perfect question</a>
</li><li><a href='http://www.catb.org/esr/faqs/smart-questions.html'>Smart questions</a>
</li><li><a href='http://www.sscce.org/'>Short, Self Contained, Correct (Compilable), Example</a>

6
HttpFetch.md Normal file

@ -0,0 +1,6 @@
#summary Fetching URLs with HTTP.
#labels http
# Fetching URLs with HTTP
See the [example in net/http](http://golang.org/pkg/net/http/#example_Get).

20
HttpStaticFiles.md Normal file

@ -0,0 +1,20 @@
#summary Serving static files with HTTP.
#labels http
# Serving Static Files with HTTP
The HTTP package provides good support for efficiently serving static files.
This is a complete Go webserver serving static files:
```
package main
import "net/http"
func main() {
panic(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))
}
```
That example is intentionally short to make a point. Using panic() to deal with an error is probably too aggressive & would produce too much output. More typical style would be:
See the [net/http documentation](http://golang.org/pkg/net/http/) and in particular the [FileServer example](http://golang.org/pkg/net/http/#example_FileServer) for more details.

@ -0,0 +1,37 @@
# IDEs and Plugins for Go
* **[Atom](http://www.atom.io)**: javascript-based editor from GitHub. Go support at [go-plus](https://github.com/joefitzgerald/go-plus)
* **[BBedit](http://www.barebones.com/products/bbedit/)**: commercial text editor for OS X.
* Basic Go support available with the module http://pine.barebones.com/extensions/Go.plist.zip
* [Go.bbpackage](https://github.com/ascarter/go.bbpackage) with clippings, ctags standard library completion, better syntax highlighting, and tools
* **[Eclipse IDE](http://www.eclipse.org/)**: Very popular open source cross-platform IDE. [GoClipse](http://code.google.com/p/goclipse/) plugin enables Go support.
* **[Emacs](https://www.gnu.org/software/emacs/)**: Extensible and customizable text editor.
* Mode file maintained at https://github.com/dominikh/go-mode.el.
* [GoFlyMake](https://github.com/dougm/goflymake) Flymake-style syntax checking for Go
* [go-errcheck.el](https://github.com/dominikh/go-errcheck.el) Errcheck integration for Emacs
* **[Gedit](http://projects.gnome.org/gedit/)**: Official text editor for the GNOME Desktop. [Plugin for Auto-Completion and Code-Formating available](https://bitbucket.org/fzzbt/go-gedit-plugin/).
* **[Gocode](https://github.com/nsf/gocode)**: An autocompletion daemon that includes support for emacs and vim.
* **[godef](https://code.google.com/p/rog-go/source/browse/exp/cmd/godef/)**: Prints the source location of definitions in Go programs. Integrates with acme and emacs.
* **[Gotags](https://github.com/jstemmer/gotags)**: Generates ctags-compatible tag files
* **[GoWorks](http://tunnelvisionlabs.com/products/demo/goworks)**: [NetBeans](http://netbeans.org/) based open source Go IDE.
* **[IntelliJ IDEA](http://www.jetbrains.com/idea/)**: Commercial cross-plattform IDE, [free Community Edition available](http://www.jetbrains.com/idea/download/index.html). [Plugin for Go](http://plugins.jetbrains.com/plugin/?idea&id=5047) support available.
* **[jEdit](http://www.jedit.org/)**: Open source cross-plattform text editor. [Syntax-highlighting file available](http://code.google.com/p/go-stuff/source/browse/editors/jEdit/go.xml).
* **[LiteIDE](http://code.google.com/p/golangide/)**: A simple, open source and cross-platform Go IDE
* **[Notepad++](http://notepad-plus-plus.org/)**: Free source code editor for Windows.
* [notepadplus-go](https://github.com/chai2010/notepadplus-go) Syntax highlighting, functions list panel (for code browsing), code completion for keywords & builtins.
* The GOnpp plugin (available **via Notepad++'s built-in Plugin Manager**) provides code completion (requires gocode), function calltips, goimports integration, and keyboard shortcuts for common go commands. [[sources](https://github.com/tike/GOnpp), [binaries](http://sourceforge.net/projects/gonpp/files/)].
* [GoAutocomplete](https://github.com/steve-perkins/GoAutocomplete) is another code completion plugin.
* **[Sublime Text](http://www.sublimetext.com/)**: Commercial text editor. [Plugin collection with IDE-like features available](https://github.com/DisposaBoy/GoSublime).
* **[TextMate](http://macromates.com/)**: Commercial text editor for OS X. [Source code available](https://github.com/textmate/textmate) under the GPLv3. [Bundle for Go available](https://github.com/AlanQuatermain/go-tmbundle).
* **[TextWrangler](http://www.barebones.com/products/textwrangler/)**: free _little brother_ of BBedit. Both the Go module and Go.bbpackage for BBedit work for TextWrangler as well.
* **[Vim](http://www.vim.org/)**: Vi Improved. There are a number of plugins available that make editing Go code easier.
* The [vim-go](https://github.com/fatih/vim-go) plugin includes misc/vim and has many other new improvements.
* The [Syntastic](https://github.com/scrooloose/syntastic) plugin gives instant feedback on compile errors
* The [tagbar](https://github.com/majutsushi/tagbar) plugin uses Gotags, above, to show an outline of the current file
* A [vim compiler plugin](https://github.com/rjohnsondev/vim-compiler-go) for syntax checking
* A [vim-godef](https://github.com/dgryski/vim-godef) plugin integrates with the 'godef' tool, above
* A [vim-go-extra](https://github.com/vim-jp/vim-go-extra) is vim plugin based on misc/vim in go repository. This works fine on windows too!
* **[GNU Nano](http://golang.cat-v.org/text-editors/nano/)**: a simple .nanorc for GNU Nano ("pico").
* **[Zeus](http://www.zeusedit.com/go.html)**: Commercial IDE for Go.
Other environments such XCode and kate also had minor support checked in to the Go tree up until Go 1.3. If you want these, search the standard repository's history. Here is a link: https://code.google.com/p/go/source/browse/misc/?name=release-branch.go1.3

27
InstallFromSource.md Normal file

@ -0,0 +1,27 @@
# Introduction
This is a companion to http://golang.org/doc/install/source providing additional instructions for various operating systems.
## Install C tools
On OS X, a C compiler is bundled in the command line tools for
[Xcode](http://developer.apple.com/Xcode/),
and you don't need to install the whole Xcode to compile Go.
If you have already installed Xcode 4.3+, you can install command
line tools from the Components tab of the Downloads preferences panel.
In more recent versions of Xcode, you can use ` xcode-select --install `
command to install the command line tools without opening Xcode.
To verify you have a working compiler, just invoke ` gcc `
in a freshly created Terminal window, unless you see the
` "gcc: command not found" ` error, you are ready to go.
On Ubuntu/Debian, use ` sudo apt-get install gcc libc6-dev `.
If you want to build 32-bit binaries on a 64-bit system you'll also need the ` libc6-dev-i386 ` package.
On RedHat/Centos 6, use ` sudo yum install gcc glibc-devel `.
If you want to build 32-bit binaries on a 64-bit system you'll need both
` glibc-devel.i386 ` and ` glibc-devel.x86_64 ` packages.
On Windows, install ` gcc ` with
[MinGW](http://www.mingw.org/).
(Make sure you add its ` bin ` subdirectory to your ` PATH `.) Go does not support the Cygwin toolchain.

55
InstallTroubleshooting.md Normal file

@ -0,0 +1,55 @@
(TODO: Add table of contents.)
# Introduction
There are many times in which you may install Go (either from source or from a binary distribution) and things don't work quite right. This page is meant to collect some common wisdom about problems that are relatively common or difficult to diagnose and provide tips and solutions.
# Tips
## Environment
To start out with, check the following first:
* GOROOT
* This should _only_ be set if you used a binary distribution and it's not installed in the default location.
* [GOPATH](http://golang.org/cmd/go#GOPATH_environment_variable)
* This should be set to the directory under which you want your source (and third party packags).
* This can also be set to a list of absolute paths separated by : (or ; on Windows).
* Note that ~/some/path is not absolute and will probably not work the way you expect (try $HOME/some/path instead).
* GOPATH should not be set to or contain GOROOT
* GOBIN
* This should only be set if you _really_ know what you're doing... The default should be fine.
* GOOS, GOARCH, GOHOSTOS, GOHOSTARCH
* You shouldn't need to set these in normal cases.
Under linux and darwin, make sure that any of the above variables which are set are actually exported. When you run the ` env | grep GO ` command, they should be listed. You can also check your environment with the ` go env ` command. In bash, this is done with the ` export GOPATH ` (if it's already set) or ` export GOPATH=/path/to/gopath ` command (similarly for the other variables), usually in your .bashrc or .bash\_profile.
## GOROOT vs GOPATH
Packages under GOROOT store their source files in
` $GOROOT/src/pkg/import/path/*.go `
Notice that this is ` src/pkg `; under GOPATH, source files are stored in
` $GOPATH/src/import/path/*.go `
Because of this inconsistency, it is generally not recommended that GOPATH be set to or contain GOROOT; its directories will be searched automatically for imports regardless of the GOPATH setting.
# Troubleshooting
## The ` go build ` command doesn't do anything!
The ` go build ` command will only produce a binary; if you run go build in a package directory, it will build the package normally (and report any compile errors), but it will not install it. For that, you use ` go install `. If you think you're building a binary and none is produced, make sure you are in package ` main ` and that you do not have GOBIN set.
## Why does ` go get ` report ` "Fetching https://runtime/cgo?go-get=1" `?
If you have a source distribution, make sure that your packages are up-to-date. Also double check the environment above.
## When cross compiling, I get ` "runtime/extern.go:135: undefined: theGoos" `
Read [WindowsCrossCompiling](wiki/WindowsCrossCompiling) for some helpful scripts. You can also use the ` --no-clean ` argument when you're building the cross-compile toolchain via ` make.bash `.
### Why does ` go get ` work for some packages and report ` permission denied ` in ` $GOROOT ` for some others (with GOPATH set properly)?
If you at any point installed the package in ` GOROOT ` (either by having no ` GOPATH ` set or by including ` GOROOT ` itself in ` GOPATH `) then there might still be a directory in ` $GOROOT ` (which is always checked first) that is overriding your ` GOPATH `. To verify, run ` go list -f {{.Dir}} importpath ` and if it reports a directory under ` $GOPATH ` try deleting that first.
## Still need help?
Visit us on IRC or ask on the mailing list. You will want to provide the output of the following commands, in addition to any errors you are getting:
```
go version
go env
env | grep GO
```

11
InstallingExp.md Normal file

@ -0,0 +1,11 @@
First, make sure you have your workspace set up (setting ` GOPATH `). See the [How to write Go code](http://golang.org/doc/code.html) document for details.
# Installing ` exp ` under ` GOPATH `
Recently, packages under exp is moved to the go.exp sub-repository.
They should be go-gettable without any special handling.
For example,
```
go get code.google.com/p/go.exp/inotify
```

42
InterfaceSlice.md Normal file

@ -0,0 +1,42 @@
# Introduction
Given that you can assign a variable of any type to an ` interface{} `, often people will try code like the following.
```
var dataSlice []int = foo()
var interfaceSlice []interface{} = dataSlice
```
This gets the error
```
cannot use dataSlice (type []int) as type []interface { } in assignment
```
The question then, "Why can't I assign any slice to an ` []interface{} `, when I can assign any type to an ` interface{} `?"
## Why?
There are two main reasons for this.
The first is that a variable with type ` []interface{} ` is not an interface! It is a slice whose element type happens to be ` interface{} `. But even given this, one might say that the meaning is clear.
Well, is it? A variable with type ` []interface{} ` has a specific memory layout, known at compile time.
Each ` interface{} ` takes up two words (one word for the type of what is contained, the other word for either the contained data or a pointer to it). As a consequence, a slice with length N and with type ` []interface{} ` is backed by a chunk of data that is N\*2 words long.
This is different than the chunk of data backing a slice with type ` []MyType ` and the same length. Its chunk of data will be N\*sizeof(MyType) words long.
The result is that you cannot quickly assign something of type ` []MyType ` to something of type ` []interface{} `; the data behind them just look different.
## What can I do instead?
It depends on what you wanted to do in the first place.
If you want a container for an arbitrary array type, and you plan on changing back to the original type before doing any indexing operations, you can just use an ` interface{} `. The code will be generic (if not compile-time type-safe) and fast.
If you really want a ` []interface{} ` because you'll be doing indexing before converting back, or you are using a particular interface type and you want to use its methods, you will have to make a copy of the slice.
```
var dataSlice []int = foo()
var interfaceSlice []interface{} = make([]interface{}, len(dataSlice))
for i, d := range dataSlice {
interfaceSlice[i] = d
}
```

32
Iota.md Normal file

@ -0,0 +1,32 @@
# Summary
Go's ` iota ` identifier is used in in ` const ` declarations to simplify definitions of incrementing numbers. Because it can be used in expressions, it provides a generality beyond that of simple enumerations.
The values of iota start at zero within each const block and increment by one each time it is seen. This can be combined with the constant shorthand (leaving out everything after the constant name) to very concisely define related constants.
Iota: http://golang.org/doc/go_spec.html#Iota
Constant declarations: http://golang.org/doc/go_spec.html#Constant_declarations
# Examples
The official spec has two great examples:
http://golang.org/doc/go_spec.html#Iota
Here's one from Effective Go:
```
type ByteSize float64
const (
_ = iota // ignore first value by assigning to blank identifier
KB ByteSize = 1<<(10*iota)
MB
GB
TB
PB
EB
ZB
YB
)
```

4
Learn.md Normal file

@ -0,0 +1,4 @@
In addition to the resources available [at golang.org](http://golang.org/doc/#learning) there are a range of community-driven initiatives:
* [Go By Example](http://gobyexample.com/) - a series of annotated code snippets.
* [Learn Go in Y minutes](http://learnxinyminutes.com/docs/go/) - a top-to-bottom walkthrough of the language.

51
LockOSThread.md Normal file

@ -0,0 +1,51 @@
# Introduction
Some libraries, especially graphical frameworks/libraries like Cocoa, OpenGL, libSDL all require it's
called from the main OS thread or called from the same OS thread due to its use of thread local
data structures. Go's runtime provides ` LockOSThread() ` function for this, but it's notoriously difficult
to use correctly.
# Solutions
Russ Cox presented a good solution for this problem in this [thread](https://groups.google.com/d/msg/golang-nuts/IiWZ2hUuLDA/SNKYYZBelsYJ).
```
package sdl
// Arrange that main.main runs on main thread.
func init() {
runtime.LockOSThread()
}
// Main runs the main SDL service loop.
// The binary's main.main must call sdl.Main() to run this loop.
// Main does not return. If the binary needs to do other work, it
// must do it in separate goroutines.
func Main() {
for f = range mainfunc {
f()
}
}
// queue of work to run in main thread.
var mainfunc = make(chan func())
// do runs f on the main thread.
func do(f func()) {
done := make(chan bool, 1)
mainfunc <- func() {
f()
done <- true
}
<-done
}
```
And then other functions you write in package sdl can be like
```
func Beep() {
do(func() {
// whatever must run in main thread
})
}
```

124
MethodSets.md Normal file

@ -0,0 +1,124 @@
(TODO: Add table of contents.)
# Introduction
Method sets of a particular type or value are of particular importance in Go, where the method set determines what interfaces a value implements.
# The Spec
There are two important clauses in the [Go Language Specification](http://golang.org/doc/go_spec.html) about method sets. They are as follows:
[Method Sets](http://golang.org/doc/go_spec.html#Method_sets):
A type may have a method set associated with it. The method set of an interface type is its interface. The method set of any other named ` type T ` consists of all methods with receiver type ` T `. The method set of the corresponding pointer type ` *T ` is the set of all methods with receiver ` *T ` or ` T ` (that is, it also contains the method set of ` T `). Any other type has an empty method set. In a method set, each method must have a unique name.
[Calls](http://golang.org/doc/go_spec.html#Calls):
A method call ` x.m() ` is valid if the method set of (the type of) ` x ` contains ` m ` and the argument list can be assigned to the parameter list of ` m `. If ` x ` is addressable and ` &x `'s method set contains ` m `, ` x.m() ` is shorthand for ` (&x).m() `.
# Usage
There are many different cases during which a method set crops up in day-to-day programming. Some of the main ones are when calling methods on variables, calling methods on slice elements, calling methods on map elements, and storing values in interfaces.
## Variables
In general, when you have a variable of a type, you can pretty much call whatever you want on it. When you combine the two rules above together, the following is valid:
```
type List []int
func (l List) Len() int { return len(l) }
func (l *List) Append(val int) { *l = append(*l, val) }
func main() {
// A bare value
var lst List
lst.Append(1)
fmt.Printf("%v (len: %d)\n", lst, lst.Len())
// A pointer value
plst := new(List)
plst.Append(2)
fmt.Printf("%v (len: %d)\n", plst, plst.Len())
}
```
Note that both pointer and value methods can both be called on both pointer and non-pointer values. To understand why, let's examine the method sets of both types, directly from the spec:
```
List
- Len() int
*List
- Len() int
- Append(int)
```
Notice that the method set for ` List ` does not actually contain ` Append(int) ` even though you can see from the above program that you can call the method without a problem. This is a result of the second spec section above. It implicitly translates the first line below into the second:
```
lst.Append(1)
(&lst).Append(1)
```
Now that the value before the dot is a ` *List `, its method set includes Append, and the call is legal.
To make it easier to remember these rules, it may be helpful to simply consider the pointer- and value-receiver methods separately from the method set. It is legal to call a pointer-valued method on anything that is already a pointer or whose address can be taken (as is the case in the above example). It is legal to call a value method on anything which is a value or whose value can be dereferenced (as is the case with any pointer; this case is specified explicitly in the spec).
## Slice Elements
Slice elements are almost identical to variables. Because they are addressable, both pointer- and value-receiver methods can be called on both pointer- and value-element slices.
## Map Elements
Map elements are not addressable. Therefore, the following is an _illegal_ operation:
```
lists := map[string]List
lists["primes"].Append(7) // cannot be rewritten as (&lists["primes"]).Append(7)
```
However, the following is still valid (and is the far more common case):
```
lists := map[string]*List
lists["primes"] = new(List)
lists["primes"].Append(7)
count := lists["primes"].Len() // can be rewritten as (*lists["primes"]).Len()
```
Thus, both pointer- and value-receiver methods can be called on pointer-element maps, but only value-receiver methods can be called on value-element maps. This is the reason that maps with struct elements are almost always made with pointer elements.
## Interfaces
The concrete value stored in an interface is not addressable, in the same way that a map element is not addressable. Therefore, when you call a method on an interface, it must either have an identical receiver type or it must be directly discernible from the concrete type: pointer- and value-receiver methods can be called with pointers and values respectively, as you would expect. Value-receiver methods can be called with pointer values because they can be dereferenced first. Pointer-receiver methods cannot be called with values, however, because the value stored inside an interface has no address. When assigning a value to an interface, the compiler ensures that all possible interface methods can actually be called on that value, and thus trying to make an improper assignment will fail on compilation. To extend the earlier example, the following describes what is valid and what is not:
```
type List []int
func (l List) Len() int { return len(l) }
func (l *List) Append(val int) { *l = append(*l, val) }
type Appender interface {
Append(int)
}
func CountInto(a Appender, start, end int) {
for i := start; i <= end; i++ {
a.Append(i)
}
}
type Lener interface {
Len() int
}
func LongEnough(l Lener) bool {
return l.Len()*10 > 42
}
func main() {
// A bare value
var lst List
CountInto(lst, 1, 10) // INVALID: Append has a pointer receiver
if LongEnough(lst) { // VALID: Identical receiver type
fmt.Printf(" - lst is long enough")
}
// A pointer value
plst := new(List)
CountInto(plst, 1, 10) // VALID: Identical receiver type
if LongEnough(plst) { // VALID: a *List can be dereferenced for the receiver
fmt.Printf(" - plst is long enough")
}
}
```

33
MultipleGoRoots.md Normal file

@ -0,0 +1,33 @@
# Introduction
Tips for hacking on Go and having multiple ` $GOROOT ` workspaces...
Sometimes you need to check out multiple copies of the Go tree, perhaps you're working on several core library changes at once and you want to test them independently. (Although Mercurial supports the kind of lightweight branching that makes it possible to develop multiple changes in one workspace, to avoid confusion, the Go project has disabled this feature to ensure that submitted code follows a strictly linear progression.)
Let's say you've checked the trees out as ` $HOME/go1 `, ` $HOME/go2 `, etc. (The specific names are not important.) While you're working in each tree, it's important that you always set ` GOROOT ` to the correct tree or unexpected things will happen, like binaries will be built from sources other than the ones you've just edited. Such mistakes can be time-consuming to notice, and it's easy to forget to update ` GOPATH ` when you change directories. The following trick may be helpful.
Define a script called ` go `, and ensure its directory is on your ` PATH ` or define a shell alias ` go ` that points to it. In the script, set the ` GOROOT ` and (if you like) ` GOPATH ` environment variables to appropriate values determined from your current working directory. Then exec the real ` go ` command.
For example:
```
#!/bin/sh
# Set GOROOT to the innermost enclosing directory containing
# an AUTHORS file. Set GOPATH to its child called "got".
dir=$(pwd)
while true; do
if [ -f "$dir/AUTHORS" ]; then
export "GOROOT=$dir"
export "GOPATH=$GOROOT/got"
echo "GOROOT=$GOROOT" >&2
echo "GOPATH=$GOPATH" >&2
break
fi
dir=$(dirname "$dir")
if [ "$dir" = / ]; then
echo "Can't locate GOROOT". >&2
exit 1
fi
done
exec "$GOROOT/bin/go" "$@"
```

24
MutexOrChannel.md Normal file

@ -0,0 +1,24 @@
# Use a sync.Mutex or a channel?
One of Go's mottos is _"Share memory by communicating, don't communicate by sharing memory."_
That said, Go does provide traditional locking mechanisms in the <a href='http://golang.org/pkg/sync/'>sync package</a>. Most locking issues can be solved using either channels or traditional locks.
So which should you use?
Use whichever is most expressive and/or most simple.
A common Go newbie mistake is to over-use channels and goroutines just because it's possible, and/or because it's fun. Don't be afraid to use a <a href='http://golang.org/pkg/sync/#Mutex'><code>sync.Mutex</code></a> if that fits your problem best. Go is pragmatic in letting you use the tools that solve your problem best and not forcing you into one style of code.
As a general guide, though:
| **Channel** | **Mutex**|
|:------------|:|
| passing ownership of data,<br />distributing units of work,<br /> communicating async results | caches,<br />state |
If you ever find your sync.Mutex locking rules are getting too complex, ask yourself whether using channel(s) might be simpler.
## More Info
* Channels in Effective Go: http://golang.org/doc/effective_go.html#channels
* The sync package: http://golang.org/pkg/sync/

18
NativeClient.md Normal file

@ -0,0 +1,18 @@
Go 1.3 includes support for generating x86-32 and x86-64 binaries for Google Native Client (NaCl).
NaCl is a collection of related technologies.
1. NaCl defines a collection of binary formats with specific code layout requirements. There are definitions for 32- and 64-bit x86 and 32-bit ARM.
1. NaCl provides a mechanism for running those binaries in a sandboxed execution environment with a restricted syscall-like interface. That syscall-like interface is not guaranteed to be stable from release to release.
1. To abstract away the syscall-like interface, NaCl defines a stable runtime API called the integrated runtime (IRT).
1. Using the IRT, Google Chrome defines an API called Pepper (aka PPAPI) that NaCl-based plugins use to interact with the browser.
1. To abstract away the machine-specific binary formats, NaCl defines an LLVM-based architecture-independent format called PNaCl.
1. NaCl provides translators from PNaCl format to the architecture-specific formats, invoked automatically, so that you can distribute just a PNaCl binary and execute on all three supported platforms.
Go 1.3 provides support for generating the architecture-specific binaries and using the raw syscall interface (1 and 2 in the list above), and only for the x86 platforms (not for ARM).
There is ongoing work exploring support for the IRT and PPAPI (3 and 4 in the list) but no definite release target. Perhaps they will be in Go 1.4 but perhaps not.
There are no concrete plans to support PNaCl (5 and 6 in the list).
The Go 1.3-generated NaCl binaries can be run using the NaCl SDK sel\_ldr\_x86\_32 and sel\_ldr\_x86\_64 programs. They cannot be run directly in Google Chrome. As such, the NaCl support in Go 1.3 is useful only for running sandboxed environments like the [Go Playground](http://play.golang.org/). The file [misc/nacl/README](http://golang.org/misc/nacl/README) in the Go distribution explains how to configure your machine so that you can run and NaCl-sandboxed binaries using the go command.

10
NetBSD.md Normal file

@ -0,0 +1,10 @@
# Go on NetBSD
Required:
* NetBSD 6.0 or later
# Preparing NetBSD for Go
* install NetBSD 6.0 (remember to install pkgsrc in the last step)
* install shells/bash and devel/mercurial (do ` make package-install clean ` in ` /usr/pkgsrc/shells/bash ` and ` /usr/pkgsrc/devel/mercurial `.
* Using binary packages: ` pkgin install bash mercurial `

48
NonEnglish.md Normal file

@ -0,0 +1,48 @@
Some of this documentation may be out of date.
## Belarusian - Беларуская
* [faq-be](http://www.designcontest.com/show/faq-be) - Frequently Asked Questions.
## Brazilian Portuguese - Português brasileiro
* [A Tour of Go](http://go-tour-br.appspot.com/)
* [golangbr.org](http://golangbr.org/) - Go documentation and news.
## Chinese - 中文
* [A Tour of Go](http://go-tour-zh.appspot.com/)
* [Go 编程语言](http://zh-golang.appspot.com/) - Chinese Translation of tip.golang.org
* [golang-china](http://code.google.com/p/golang-china/) - a broad range of Go documentation.
* [Effective Go and (old) Tutorial](http://code.google.com/p/ac-me/downloads/detail?name=fango.pdf)
## Czech - Čeština
* [Pravidla reflexe](http://www.abclinuxu.cz/clanky/google-go-pravidla-reflexe) - a translation of [The Laws of Reflection](http://blog.golang.org/2011/09/laws-of-reflection.html).
## French - Français
* [golang-france](http://code.google.com/p/golang-france/) - Go documentation.
## German - Deutsch
* [Eine Anleitung zum Programmieren in Go](http://bitloeffel.de/DOC/golang/go_tutorial_de.html) - the (old) Go Tutorial.
* [Wirkungsvoll Go programmieren](http://bitloeffel.de/DOC/golang/effective_go_de.html) - Effective Go.
* [Wie man Go-Kode schreibt](http://bitloeffel.de/DOC/golang/code_de.html) - How to Write Go Code.
* [Deutschsprachige Go Themenseite - German Go resource page](http://www.hweidner.de/golang)
## Japanese - 日本語
* [A Tour of Go](http://go-tour-jp.appspot.com/)
* [golang.jp](http://golang.jp/) - Go documentation and news.
## Korean - 한국어
* [A Tour of Go](http://go-tour-kr.appspot.com)
* [golang-korea](http://code.google.com/p/golang-korea) - Go documentation and news.
## Turkish - Türkçe
* [A Tour of Go](http://tur.a.golang.org.tr/)

22
OlderVersions.md Normal file

@ -0,0 +1,22 @@
# Introduction
This wiki page collects patches to build older version of Go on newer systems for
testing and benchmark purposes. Please note that older Go versions are not
supported, so don't use older version in production.
# Go 1.0.x
## Go 1.0
```
diff -ur go/src/cmd/cc/funct.c go1/src/cmd/cc/funct.c
--- go/src/cmd/cc/funct.c 2012-03-28 00:49:24.000000000 -0400
+++ go1/src/cmd/cc/funct.c 2014-05-04 00:56:00.971460175 -0400
@@ -269,7 +269,7 @@
goto bad;
f = alloc(sizeof(*f));
- for(o=0; o<sizeof(f->sym); o++)
+ for(o=0; o<nelem(f->sym); o++)
f->sym[o] = S;
t->funct = f;
```

75
OpenBSD.md Normal file

@ -0,0 +1,75 @@
# Go on OpenBSD
Required:
* OpenBSD amd64, 386: 5.5
* If you want to run go1.3 or 1.4 on OpenBSD 5.6, see http://golang.org/issue/9102
| **Kernel version** | **Min. version** | **Max. version**|
|:-------------------|:-----------------|:|
| 5.6 | go1.5 | go1.5 |
| 5.5 | go1.3 | go1.5 |
* ulimits (` /etc/login.conf `)
Edit the /etc/login.conf so that the staff class has the proper
settings. The following is a working example of the staff class:
```
staff:\
:datasize-cur=infinity:\
:datasize-max=infinity:\
:datasize=infinity:\
:openfiles-cur=4096:\
:maxproc-max=512:\
:maxproc-cur=512:\
:ignorenologin:\
:requirehome@:\
:tc=default:
```
After editing the login.conf you'll need to rebuild the database with:
```
# cap_mkdb /etc/login.conf
```
```
ulimit -n 512
ulimit -p 512
ulimit -d 2036792
```
Add the login class to the user you would like to have build go
```
# vipw
```
Look for the 5th element which is the login class, this is blank by
users added by useradd. In the following example the user operator
would be added to the staff class
```
## Before
operator:*:2:5::0:0:System &:/operator:/sbin/nologin
## After
operator:*:2:5:staff:0:0:System &:/operator:/sbin/nologin
```
## Under KVM
If under KVM on Lucid, you don't need to disable ` mpbios `, but the OpenBSD kernel spins at takes nearly 100% CPU if you don't. So, see:
http://scie.nti.st/2009/10/4/running-openbsd-4-5-in-kvm-on-ubuntu-linux-9-04
Nutshell:
```
# config -ef /bsd
OpenBSD 4.5 (GENERIC) #2052: Sat Feb 28 14:55:24 MST 2009
deraadt@amd64.openbsd.org:/usr/src/sys/arch/amd64/compile/GENERIC
Enter 'help' for information
ukc> disable mpbios
54 mpbios0 disabled
ukc> quit
Saving modified kernel.
#
```

180
PackageManagementTools.md Normal file

@ -0,0 +1,180 @@
This page contains a list of tools for managing Go packages and their dependencies. The tools are divided into categories based on their approach to version management.
The approach [endorsed by the Go project](http://golang.org/doc/faq#get_version) is "vendoring" (described below) and [godep](https://github.com/tools/godep) is a well-maintained tool for managing vendored dependencies.
## Vendoring
Vendoring takes the 3rd party source code that is referenced in your project and makes a copy of that code inside a new folder within the project. All the code your project needs is inside the one project repository. Vendoring also provides a performance enhancement on getting the code because only one url call is required.
| **godep** |https://github.com/tools/godep|
|:----------|:-----------------------------|
|Title |Helps build packages reproducibly by fixing their dependencies|
|Author |Keith Rarick |
|Categories |Vendoring, Revision Locking (git, mercurial, bazaar)|
| | |
| **godeps** |https://github.com/dre1080/godeps|
|Title |Simple dependency management for Go|
|Author |andoooooo |
|Categories |Vendoring |
|Notes |Requires goven. godeps is a unix shell script.|
| | |
| **gom** |https://github.com/mattn/gom |
|Title |Go Manager - bundle for go |
|Author |Yasuhiro Matsumoto |
|Categories |Vendoring/Bundling |
| | |
| **gondler** |https://github.com/rosylilly/gondler|
|Title |Bundler for golang |
|Author |Sho Kusano |
|Categories |Vendoring/Bundling/Revision Locking|
| | |
| **goop** |https://github.com/nitrous-io/goop|
|Title |A dependency manager for Go (golang), inspired by Bundler.|
|Author |Nitrous.IO |
|Categories |Vendoring, Revision Locking |
| | |
| **goven** |https://github.com/kr/goven |
|Title |Vendor Go packages |
|Author |Keith Rarick |
|Categories |Vendoring |
|Notes |Now suggests using github.com/tools/godep|
| | |
| **third-party** |https://github.com/coreos/third_party.go|
|Title |Self contained GOPATH helper |
|Author |CoreOS |
|Categories |Vendoring |
|Notes |CoreOS now uses github.com/tools/godep|
| | |
| **vendorize** |https://github.com/kisielk/vendorize|
|Author |Kamil Kisiel |
|Categories |Vendoring |
| | |
| **party** |https://github.com/mjibson/party|
|Author |Matt Jibson |
|Categories |Vendoring |
## Revision Locking
Revision Locking creates a dependency file that references specific commits in the different version control systems the code is located in. Just like vendoring, the RL tool is used to get, build and install your project. One advantage is that your project repository continues to only contain the specific project code.
| **depman** |https://github.com/vube/depman|
|:-----------|:-----------------------------|
|Title |Supports versioned dependencies, using standard Golang imports|
|Author |vube.com |
|Categories |Revision Locking (git, mercurial, bazaar)|
| | |
| **dondur** |https://github.com/oguzbilgic/dondur|
|Title |Freeze your Go dependencies with ease|
|Author |Oguz Bilgic |
|Categories |Revision Locking (git, mercurial, bazaar)|
| | |
| **envie** |https://github.com/sam-falvo/envie|
|Title |Download and manage Go projects and their dependencies|
|Author |Samuel A. Falvo II |
|Categories |Revision Locking (unknown) |
| | |
| **glock** |https://github.com/robfig/glock|
|Title |Lock dependencies to specific revisions.|
|Author |Rob Figueiredo |
|Categories |Revision Locking (git) |
| | |
| **gobs** |https://bitbucket.org/vegansk/gobs|
|Title |Build system and package manager for go language|
|Author |Anatoly Galiulin |
|Categories |Revision Locking (git) |
| | |
| **godep** |https://github.com/tools/godep|
|Title |Helps build packages reproducibly by fixing their dependencies|
|Author |Keith Rarick |
|Categories |Vendoring, Revision Locking (git, mercurial, bazaar)|
| | |
| **godeps** |https://launchpad.net/godeps |
|Title |Print, fetch and update dependencies with care. In production use by Canonical. The first tool with this name!|
|Author |Roger Peppe |
|Categories | Revision Locking (git, mercurial, bzr)|
| **gopack** |https://github.com/d2fn/gopack|
|Title |Dependency management for go inspired by rebar|
|Author |Dietrich Featherston |
|Categories |Revision Locking (git) |
| | |
| **gopin** |https://github.com/laher/gopin|
|Title |Experimental go-get fork with support for tags and alternative repos|
|Author |Go Package Manager |
|Categories |Revision Locking (git) |
| | |
| **gopm** |https://github.com/GPMGo/gopm |
|Title |Tool for search, install, update, share packages in Go|
|Author |Am Laher |
|Categories |Revision Locking (git, mercurial, bazaar)|
| | |
| **gpm** |https://github.com/pote/gpm |
|Title |Barebones dependency manager for Go.|
|Author |Pablo Astigarraga |
|Categories |Revision Locking (git, mercurial, bazaar)|
| | |
| **johnny deps** |https://github.com/VividCortex/johnny-deps|
|Title |Barebones dependency manager for Go|
|Author |Baron Schwartz / Gustavo Kristic|
|Categories |Revision Locking (git) |
| | |
| **pack** |https://github.com/theplant/pak|
|Title |Simple package management tool for Go|
|Author |The Plant |
|Categories |Revision Locking (git) |
| | |
| **rx** |http://godoc.org/kylelemons.net/go/rx|
|Title |[Automation for dependency management tasks](http://kylelemons.net/blog/2012/04/22-rx-for-go-headaches.article)|
|Author |Kyle Lemons |
|Categories |Revision Locking (git, mercurial)|
## Import Proxies
Import Proxies act as a man in the middle between the Go tool and the VCS. It parses the data stream while the repository is being cloned.
| **git-version-proxy** |https://github.com/msiebuhr/git-version-proxy|
|:----------------------|:--------------------------------------------|
|Title |A HTTP Git proxy that only exposes certain versions|
|Author |Morten Siebuhr |
|Categories |Import Proxy (git) |
| | |
| **gopin** |http://gopin.org |
|Title |Tool-less version pinning for Go |
|Author |Alexander Suma |
|Categories |Import Proxy (GitHub) |
| | |
| **gopkg.in** |https://gopkg.in |
|Title |Redirect the go tool onto well defined GitHub repositories. Versioning with tags and branches or the repository name.|
|Author |Gustavo Niemeyer |
|Categories |Import Proxy (GitHub) |
| | |
| **gopkg.cc** |http://gopkg.cc |
|Title |Exposes each branch and tag in a GitHub repository at a separate package path|
|Author |Simon Menke |
|Categories |Import Proxy (GitHub) |
## Go Version Managers
Go Version Managers allow you to have multiple versions of Go installed on your machine. It allows you to switch between those versions.
| **gvm** |https://github.com/moovweb/gvm|
|:--------|:-----------------------------|
|Title |Go Version Manager |
|Author |Josh Bussdieker |
|Categories|Go Version Manager |
## Unclassified
Not able to classify these tools.
| **go-dep** |https://github.com/go-dep/dep|
|:-----------|:----------------------------|
|Title |Go package dependencies with the help of the Go Dependency Format (GDF)|
|Author |Marc Rene Arns |
|Categories |Not Sure |
## Client App Test Packages
Here is a list of packages that authors can use to test their tools against.
| **beego-mgo** |https://github.com/goinggo/beego-mgo|
|:--------------|:-----------------------------------|
|Author |Bill Kennedy |
|Desc |Sample Application For Using the Beego web framework with MGO|
| | |
| **revel-mgo** |https://github.com/goinggo/revel-mgo|
|Author |Bill Kennedy |
|Desc |Sample revel project with mgo support|

125
PackagePublishing.md Normal file

@ -0,0 +1,125 @@
# Introduction
Now that you've spent many hours writing your package and debugging it and testing it (you did [test it](wiki/TableDrivenTests), didn't you?), you want to publish it so other people can [goinstall](http://golang.org/cmd/goinstall) your package and see it on the [dashboard](http://godashboard.appspot.com/package).
First, you will need to host it online somewhere. Four major code hosting sites are [bitbucket](http://bitbucket.org/) (hg), [github](http://github.com/) (git), [googlecode](http://code.google.com/projecthosting/) (hg/git/svn), and [launchpad](http://launchpad.net) (bzr). I recommend choosing whichever version control system you are familiar with or which your code is versioned locally on your machine. Mercurial (hg) is the version control system used by the central Go repository, so it is the closest to a guarantee as you can get that a developer wanting to use your project will have the right software. Git is also very popular, and so is also often available. If you have never used version control before, these websites have some nice HOWTOs and you can find many great tutorials by searching Google for "{name} tutorial" where {name} is the name of the version control system you would like to learn.
# Package Setup
## Choosing the Import
The full import of your package often has something identifying its author (particularly on hosting sites like github, where "github.com/kylelemons/..." is the full import), should always have the project name, and should end with the name of the package you've developed if it is different from the project name. For instance, the go-gypsy project provides a yaml package, and is written by Kyle Lemons, and thus has the following import path:
```
import "github.com/kylelemons/go-gypsy/yaml"
^ ^ ^ ^
| | | `-- Package name
| | `-------- Project name
| `------------------- Author's handle
`----------------------------- Hosting site
```
As of the time of this writing, the current release (r60 (on Google Code)) does support subdirectories of package repositories, but if you are going to be supporting earlier versions, note that they may not have a goinstall binary which reports subdirectories within a repository to the dashboard.
## Subdirectories
Frequently, the name that you use for your package will include the name "Go" as a prefix, suffix, or part of its acronym, and you may or may not want this to be a part of the actual command or package name in a go source file. Often, you may have both libraries and commands as a part of your package, and these cannot coexist in the same directory. When these things happen, you will want to structure your repository with subdirectories.
For example, consider a project "Go-PublishingExample" that provides a "epub" package and a "publish" command. The directory structure could be:
```
./epub/ # Package source, all files package "epub"
./publish/ # Command source
./doc/ # Documentation which won't be downloaded
./examples/ # Example code which won't be downloaded
```
The import statement for the package would look like:
```
import "codesite.tld/authorName/Go-PublishingExample/epub"
```
It is often a good idea to make sure the last directory path (in this case, "epub") matches the name of the package used by the source files in the directory. In this case, no goinstallable files were included in the base directory because neither the binary nor the package were to be named "Go-PublishingExample".
## Branches and Tags
In general, the Go source tree can exist in three basic states. It can be checked out at a Go Release branch (r60 (on Google Code) at the time of this writing -- this is where most users should be), or it can be checked out at a Go Weekly (a new tag for which is made roughly once per week), or at tip (the Mercurial term for the latest change). The last two are primarily for developers of the Go language itself or developers who need features or fixes which have not been introduced into the latest Release.
Due to the lielihood that you might continue collaborating on your project with your team on code that is not ready for general consumption, it is recommended that you utilize the tagging or branching functionality of your version control system. The goinstall tool understands some special tags and branches, which you may want to use to ensure users get a compatible version of your package:
```
go.r60 -- A "go.r##" tag will be checked out if the user has that Go release installed
go.weekly.2011-07-19 -- A "go.weekly.YYYY-MM-DD" tag will be checked out if the user has that weekly installed
```
Goinstall will attempt to fall back to the previous tag if the installed one has no matches, and if none are found, will default to installing tip.
To create and maintain your release tag in mercurial:
```
# Create or update a release tag
hg tag myProj-v0.0 # tag an easy-to-remember version number if you wish
hg tag go.r60 # tag this as being go release.r60 compatible
```
To create and maintain a release branch in git:
```
# Create a release branch
git tag myProj-v0.0 # Tag an easy-to-remember version number if you wish
git checkout -b go.r60 # create a release branch
git checkout master # to switch back to your master branch
# Update the release branch
git checkout go.r60 # switch to the release branch
git merge master # merge in changes from the master branch since last release
git checkout master # switch back to master branch
```
If you are using other branch names, substitute those names where necessary.
It will typically not be necessary to maintain weekly tags or branches, but it can be very useful to maintain the release branch or tag, as this will ensure the widest audience for your project.
## Commands vs Packages
Since goinstall does not use your project's Makefiles, it is important to understand how it will actually build your project.
All files in the same directory should always share the same package name. Any files named with a ` _test ` or an ` _os ` and/or ` _arch ` suffix will be ignored (unless the os/arch match). If the package name is "main", goinstall will build an executable from the source files and name it according to the directory name (using the last path segment only). If the package name is anything else, goinstall will build it as a package and the import path will be the web-accessible URL for your project's root followed by the subdirectory. See [the goisntall documentation](http://golang.org/cmd/goinstall) for how to make import paths for code hosting sites other than the main four.
Dependencies between packages in the same project are common. In the case where one package or command in your project depends upon another, you must use the full import path in order for goinstall to recognize the dependency and make sure it is built. Third-party packages which are imported from source files in your project will also be automatically downloaded and installed by goinstall if it is not already present.
To reuse the example above, the file ` ./publish/main.go ` may look something like this:
```
package main
import (
"flag"
)
import "codesite.tld/authorName/Go-PublishingExample/epub"
var dir = flag.String("dir", ".", "Directory to publish")
func main() {
flag.Parse()
epub.Publish(*dir)
}
```
A user wishing to install this executable would execute:
```
goinstall codesite.tld/authorName/Go-PublishingExample/publish
```
which would also install the ` ".../epub" ` package because of the dependency. A developer simply wishing to install the library could execute:
```
goinstall codesite.tld/authorName/Go-PublishingExample/epub
```
and (if he had not already installed ` publish `) would only download and install the package. Note that in none of these cases are the examples or documentation downloaded; in most cases these would be available to browse via the code site.
# Documentation
## godoc
When you are preparing to publish a package, you should make sure that the documentation looks correct by running a local copy of godoc. If your package is installed to the go package tree, you can use the following command:
```
godoc -http=:6060 &
```
Then browse to http://localhost:6060/pkg/ and find your package.
## Dashboard
The Go Dashboard will use the first line of your package-level comment (also using the normal godoc format) as the "info" text, so make sure this is set. For instance:
```
// Package epub is an example publishing library.
package epub
```
For more information on godoc, see the [Documenting Go Code](http://blog.golang.org/2011/03/godoc-documenting-go-code.html) blog post.

84
PanicAndRecover.md Normal file

@ -0,0 +1,84 @@
(TODO: Add table of contents.)
# Panic
The ` panic ` and ` recover ` functions behave similarly to exceptions and try/catch in some other languages in that a ` panic ` causes the program stack to begin unwinding and ` recover ` can stop it. Deferred functions are still executed as the stack unwinds. If ` recover ` is called inside such a deferred function, the stack stops unwinding and ` recover ` returns the value (as an ` interface{ `}) that was passed to ` panic `. The runtime will also panic in extraordinary circumstances, such as indexing an array or slice out-of-bounds. If a ` panic ` causes the stack to unwind outside of any executing goroutine (e.g. ` main ` or the top-level function given to ` go ` fail to recover from it), the program exits with a stack trace of all executing goroutines. A ` panic ` cannot be ` recover `ed by a different goroutine.
# Usage in a Package
By convention, no explicit panic() should be allowed to cross a package boundary. Indicating error conditions to callers should be done by returning error value. Within a package, however, especially if there are deeply nested calls to non-exported functions, it can be useful (and improve readability) to use panic to indicate error conditions which should be translated into error for the calling function. Below is an admittedly contrived example of a way in which a nested function and an exported function may interact via this panic-on-error relationship.
```
// A ParseError indicates an error in converting a word into an integer.
type ParseError struct {
Index int // The index into the space-separated list of words.
Word string // The word that generated the parse error.
Error error // The raw error that precipitated this error, if any.
}
// String returns a human-readable error message.
func (e *ParseError) String() string {
return fmt.Sprintf("pkg: error parsing %q as int", e.Word)
}
// Parse parses the space-separated words in in put as integers.
func Parse(input string) (numbers []int, err error) {
defer func() {
if r := recover(); r != nil {
var ok bool
err, ok = r.(error)
if !ok {
err = fmt.Errorf("pkg: %v", r)
}
}
}()
fields := strings.Fields(input)
numbers = fields2numbers(fields)
return
}
func fields2numbers(fields []string) (numbers []int) {
if len(fields) == 0 {
panic("no words to parse")
}
for idx, field := range fields {
num, err := strconv.Atoi(field)
if err != nil {
panic(&ParseError{idx, field, err})
}
numbers = append(numbers, num)
}
return
}
```
To demonstrate the behavior, consider the following main function:
```
func main() {
var examples = []string{
"1 2 3 4 5",
"100 50 25 12.5 6.25",
"2 + 2 = 4",
"1st class",
"",
}
for _, ex := range examples {
fmt.Printf("Parsing %q:\n ", ex)
nums, err := Parse(ex)
if err != nil {
fmt.Println(err)
continue
}
fmt.Println(nums)
}
}
```
# References
[Defer, Panic and Recover](http://blog.golang.org/2010/08/defer-panic-and-recover.html)
http://golang.org/doc/go_spec.html#Handling_panics
http://golang.org/doc/go_spec.html#Run_time_panics

71
PerfDashboard.md Normal file

@ -0,0 +1,71 @@
# Introduction
[Performance Dashboard](http://build.golang.org/perf) does continuous monitoring of performance characteristics of the Go implementation. It notifies codereview threads about any significant changes caused by the commit, allows to see performance changes caused by [recent commits](http://build.golang.org/perf), allows to investigate changes [in detail](http://build.golang.org/perfdetail?commit=fb3d6c1631c3f3141f33a01afb4c0a23ef0ea2cf&commit0=82f48826c6c79a3d5697d5e06cac8451f3dc3c7f&kind=builder&builder=linux-amd64-perf&benchmark=http) as well as shows [graphical representation](http://build.golang.org/perfgraph) of performance dynamics.
# Builders
The dashboard uses two builders: linux-amd64 running Ubuntu 14.04 and windows-amd64 running Windows 8.1. Both builders has the same hardware: 2 x Intel Xeon E5620 @ 2.4GHz, 8 HT cores, 12GB RAM.
# Benchmarks
The builders run benchmarks from the [go.benchmarks](https://code.google.com/p/go/source/browse?repo=benchmarks) repo:
* ` json `: marshals and unmarshals large json object, in several goroutines independently.
* ` http `: http client and server serving "hello world", uses persistent connections and read/write timeouts.
* ` garbage `: parses net package using go/parser, in a loop in several goroutines; half of packages are instantly discarded, the other half is preserved indefinitely; this creates significant pressure on the garbage collector.
* ` build `: does 'go build -a std'.
# Metrics
Metrics collected are:
* ` allocated `: amount of memory allocated, per iteration, in bytes
* ` allocs `: number of memory allocations, per iteration
* ` cputime `: total CPU time (user+sys from time Unix utility output), can be larger than time when GOMAXPROCS>1, per iteration, in ns
* ` gc-pause-one `: duration of a single garbage collector pause, in ns
* ` gc-pause-total `: total duration of garbage collector pauses, per iteration, ns
* ` latency-50/95/99 `: request latency percentile, in ns
* ` rss `: max memory consumption as reported by OS, in bytes
* ` sys-gc `: memory consumed by garbage collector metadata (` MemStats.GCSys `), in bytes
* ` sys-heap `: memory consumed by heap (` MemStats.HeapSys `), in bytes
* ` sys-other `: unclassified memory consumption (` MemStats.OtherSys `), in bytes
* ` sys-stack `: memory consumed by stacks (` MemStats.StackSys `), in bytes
* ` sys-total `: total memory allocated from OS (` MemStats.Sys `), in bytes
* ` time `: real time (essentially the same as std Go benchmarks output), per iteration, in ns
* ` virtual-mem `: virtual memory consumption as reported by OS, in bytes
And for build benchmark:
* ` binary-size `: size of the go command, in bytes
* ` build-cputime `: CPU time spent on the build, in ns
* ` build-rss `: max memory consumption of the build process as reported by OS, in bytes
* ` build-time `: real time of the build, in ns
# Profiles
The dashboard also collects a set of profiles for every commit, they are available from the [details page](http://build.golang.org/perfdetail?commit=fb3d6c1631c3f3141f33a01afb4c0a23ef0ea2cf&commit0=82f48826c6c79a3d5697d5e06cac8451f3dc3c7f&kind=builder&builder=linux-amd64-perf&benchmark=http). For usual benchmarks [CPU](http://build.golang.org/log/b023711522ca6511f2c9bfb46cdfb511fd77e967) and [memory](http://build.golang.org/log/06bd072aa0dec4936a05b7aa13b9f906b6989865) profiles are collected. For build benchmark - [perf profile](http://build.golang.org/log/34c4f0c7b7ea3521e5356b91775a026607e72d44), [per-process split of CPU time](http://build.golang.org/log/da517b4f6892af8a6b4900dbe58311b665ced00f) and [per-section size](http://build.golang.org/log/fc4287d6a9e280bf35c572c038dbc4414d60bcf8).
# Perf Changes View
The [view](http://build.golang.org/perf) allows to see aggregate information about significant performance changes caused by recent commits.
Rows:
* The first row shows difference between the latest release and tip.
* The rest of the rows show deltas caused by individual commits.
Columns:
* The first column is commit hash.
* Second - number of benchmarks that were executed for the commit to far.
* Third - metric name, or the special 'failure' metric for build/runtime crashes.
* Fourth - negative deltas.
* Fifth - positive deltas.
* The rest describe commit.
You can click on any positive/negative delta to see details about the change.
# Perf Graphs View
The [view](http://build.golang.org/perfgraph) shows dynamics of performance metrics in graphical form.
On the left pane you select one or more builders, benchmarks, metrics, GOMAXPROCS values as well as commit range, and click Refresh to update the graph.
If you hover over the graph, you see information about the commit and metric values. You can zoom in/out by scrolling (mouse wheel), and see older/newer commits by dragging the graph. Right mouse click on the graph resets view to initial.
All lines are normalized to their starting point. The first point is always 1.0, and the rest are relative to the first point.

53
PortingPolicy.md Normal file

@ -0,0 +1,53 @@
# Introduction
This document is about the policy for adding a new port to the main Go repository. By port we mean an operating system + architecture combination, such as linux/386.
The goal of this policy is to avoid the accumulation of incomplete or broken ports.
# Requirements for a new port
Before any code relating to a port can be added to the main Go repository, the following must all be done:
* At least one developer must be named (and agree) to maintain the port, by making required updates in a timely manner as architecture or operating system requirements change.
* A developer must be named (and agree) to maintain the builder, the machine trying each hg revision and providing data for http://build.golang.org.
* The builder must already be running (and failing, because the code is not yet in the main repository).
* All CLs necessary to run all.bash successfully must have been sent for review. Typically this will be a handful of CLs split by the part of the tree they change.
Once those conditions are satisfied, the Go team can accept the port and begin to merge the CLs. Once the CLs are all submitted, all.bash must pass, so that the builder reports "ok" in the dashboard.
Any port started during a release cycle must be finished (all.bash passing, builder reporting "ok") before the corresponding release freeze, or else the code will be removed at the freeze.
Because having any port entails a certain maintenance burden on the entire Go development team, not just the port's maintainer, the Go team may refuse a port meeting the above criteria if the port is judged not to reach enough users. This exception is intended to be used rarely, mainly to avoid maintaining ports for toy or hobby operating systems or experimental hardware that is not widely available.
# First class ports
Some ports are considered "first class". The distinction is mostly about releases and distribution.
A first class port has these properties:
* Broken builds block releases
* All contributors are effectively responsible for these ports (You break it, you fix it, or find someone who can.)
* Official binaries are provided
* Requires Google's Go team to own the builder machine
* Installation is documented at http://golang.org/doc/install
Graduating a port to "first class" is at the discretion of the Go team at Google.
# Removing a port
If a builder for a particular port starts failing, the code should be corrected as soon as possible; otherwise future regressions cannot be detected, and the amount of work required to bring the builder back to "ok" compounds.
Ultimately the job of making the port work again falls to the developer maintaining the port, although simple cases (such as +build lines in new code) can and should be fixed by others.
If a builder fails for more than two weeks, it is time to start looking for a more active maintainer for the port.
If a builder fails for more than four weeks or is failing at the time of a release freeze, and a new maintainer cannot be found, the port will be removed from the tree.
Due to backwards compatibility concerns, removing a formerly working port should be a last resort. Finding a new maintainer is always preferable.
# Comments and Questions
Comments or questions about the policy should be sent to golang-dev.

1277
Projects.md Normal file

File diff suppressed because it is too large Load Diff

19
ProviderIntegration.md Normal file

@ -0,0 +1,19 @@
# Introduction
A number of Platform-as-a-Service ([PaaS](http://en.wikipedia.org/wiki/Platform_as_a_service)) providers allow you to use Go applications on their clouds.
# Details
| PaaS | Repository | Quickstart Guide |
|:-----|:-----------|:-----------------|
| [Google App Engine](http://developers.google.com/appengine/) | https://github.com/GoogleCloudPlatform/appengine-plus-go | https://developers.google.com/appengine/training/go-plus-appengine/ |
| [Windows Azure](http://www.windowsazure.com/) | | http://sanatgersappa.blogspot.nl/2012/11/serving-go-using-fastcgi-on-windows.html |
| [IBM BlueMix](http://www.ibm.com/bluemix) | | http://www.ibm.com/developerworks/cloud/library/cl-bluemix-go-app/ |
| [CloudBees](http://www.cloudbees.com) | https://github.com/CloudBees-community/golang-clickstart | |
| [Cloud Foundry](http://www.cloudfoundry.com/) | https://github.com/kr/heroku-buildpack-go | http://catdevrandom.me/blog/2013/05/16/buildpacks-in-cloud-foundry-v2/ |
| [dotCloud](http://www.dotcloud.com) | https://github.com/kencochrane/golang-on-dotcloud | http://blog.dotcloud.com/go-on-dotcloud |
| [AWS Elastic Beanstalk](https://aws.amazon.com/en/elasticbeanstalk/) | https://github.com/sqs/go-elasticbeanstalk | |
| [Heroku](http://www.heroku.com) | https://github.com/kr/heroku-buildpack-go | http://mmcgrana.github.com/2012/09/getting-started-with-go-on-heroku.html |
| [OpenShift](http://openshift.redhat.com) | https://github.com/gcmurphy/golang-openshift | |
| [Stackato](http://www.activestate.com/stackato) | https://github.com/kr/heroku-buildpack-go | http://docs.stackato.com/user/deploy/languages/go.html |
| [Tsuru](http://www.tsuru.io/) | | http://docs.tsuru.io/en/latest/apps/quickstart/go.html |

2
RaceDetector.md Normal file

@ -0,0 +1,2 @@
Moved to http://golang.org/doc/articles/race_detector.html

56
Range.md Normal file

@ -0,0 +1,56 @@
# Range Clauses
Spec: http://golang.org/doc/go_spec.html#For_statements
## Summary
A range clause provides a way to iterate over a array, slice, string, map, or channel.
## Example
```
for k, v := range myMap {
log.Printf("key=%v, value=%v", k, v)
}
for v := range myChannel {
log.Printf("value=%v", v)
}
for i, v := range myArray {
log.Printf("array value at [%d]=%v", i, v)
}
```
## Reference
If only one value is used on the left of a range expression, it is the 1st value in this table.
| Range expression | 1st value | 2nd value (optional) | notes |
|:-----------------|:----------|:---------------------|:------|
| array or slice a ` [n]E `, ` *[n]E `, or ` []E ` | index ` i int ` | ` a[i] ` E |
| string s string type | index ` i int ` | rune ` int ` | range iterates over Unicode code points, not bytes |
| map m ` map[K]V ` | key ` k K ` | value ` m[k] ` V |
| channel c chan E | element ` e E ` | _none_ |
## Gotchas
When iterating over a slice or map of values, one might try this:
```
items := make([]map[int]int, 10)
for _, item := range items {
item = make(map[int]int, 1) // Oops! item is only a copy of the slice element.
item[1] = 2 // This 'item' will be lost on the next iteration.
}
```
The ` make ` and assignment look like they might work, but the value property of ` range ` (stored here as ` item `) is a _copy_ of the value from ` items `, not a pointer to the value in ` items `. The following will work:
```
items := make([]map[int]int, 10)
for i := range items {
items[i] = make(map[int]int, 1)
items[i][1] = 2
}
```

149
RateLimiting.md Normal file

@ -0,0 +1,149 @@
# Rate Limiting
## Time Tick based Approach
To limit the rate of operations per unit time, use time.Tick:
```
import "time"
rate_per_sec := 10
throttle := time.Tick(1e9 / rate_per_sec)
for req := range requests {
<-throttle // rate limit our Service.Method RPCs
go client.Call("Service.Method", req, ...)
}
```
To allow some bursts, add a buffer to the throttle:
```
import "time"
rate_per_sec := 10
burst_limit := 100
tick := time.NewTicker(1e9 / rate_per_sec)
defer tick.Stop()
throttle := make(chan int64, burst_limit)
go func() {
for ns := range tick {
select {
case: throttle <- ns
default:
}
} // exits after tick.Stop()
}()
for req := range requests {
<-throttle // rate limit our Service.Method RPCs
go client.Call("Service.Method", req, ...)
}
```
## Simpler Approach that doesn't need channels or go routines
Here is a simpler approach that relies on the notion of elapsed time to provide rate control. It is implemented as a package so others can readily use it.
```
//
// Ratelimiting incoming connections - Small Library
//
// (c) 2013 Sudhi Herle <sudhi-dot-herle-at-gmail-com>
//
// License: GPLv2
//
// Notes:
// - This is a very simple interface for rate limiting. It
// implements a token bucket algorithm
// - Based on Anti Huimaa's very clever token bucket algorithm.
//
// Usage:
// rl = NewRateLimiter(rate)
//
// ....
// if rl.Limit() {
// drop_connection(conn)
// }
//
package ratelimit
import "time"
type Ratelimiter struct {
rate int // conn/sec
last time.Time // last time we were polled/asked
allowance float64
}
// Create new rate limiter that limits at rate/sec
func NewRateLimiter(rate int) (*Ratelimiter, error) {
r := Ratelimiter{rate:rate, last:time.Now()}
r.allowance = float64(r.rate)
return &r, nil
}
// Return true if the current call exceeds the set rate, false
// otherwise
func (r* Ratelimiter) Limit() bool {
// handle cases where rate in config file is unset - defaulting
// to "0" (unlimited)
if r.rate == 0 {
return false
}
rate := float64(r.rate)
now := time.Now()
elapsed := now.Sub(r.last)
r.last = now
r.allowance += float64(elapsed) * rate
// Clamp number of tokens in the bucket. Don't let it get
// unboundedly large
if r.allowance > rate {
r.allowance = rate
}
var ret bool
if r.allowance < 1.0 {
ret = true
} else {
r.allowance -= 1.0
ret = false
}
return ret
}
```
Using this package is quite easy:
```
// rate limit at 100/s
nl = ratelimit.NewRateLimiter(100)
....
// in your event loop or network accept loop, do:
if rl.Limit() {
// drop the connection etc.
// i.e., this new event has exceeded the rate of 100/s
...
}
else {
// .. rate is not exceeded, process as needed
...
}
```
[Anti Huimaa](http://stackoverflow.com/questions/667508/whats-a-good-rate-limiting-algorithm) came up with this simple algorithm.
# References
time.Tick: http://golang.org/pkg/time/#Tick

29
Rationales.md Normal file

@ -0,0 +1,29 @@
# Introduction
This wiki entry will try to document the rationales behind some important language
decisions besides what's included in the Go FAQ and Effective Go.
# Language Features
### Why method receiver's base type cannot be pointer or interface?
Reference: https://groups.google.com/forum/#!topic/golang-nuts/aqTwXHaSC_Y
Go doesn't allow receiver's base type to be pointer to avoid possible ambiguity.
Suppose you have:
```
type T blah
type P *T
func (t *T) String() string { ... }
func (p P) String() string { ... }
var p P
```
Then the meaning of the expression ` (*p).String() ` is ambiguous, because it can refer to
both ` (*T).String ` and ` P.String `.
Go doesn't allow receiver's base type to be interfaces, because interfaces already have methods. (TODO)
# Memory Model
# Standard Library

29
SQLDrivers.md Normal file

@ -0,0 +1,29 @@
# SQL database drivers
The database/sql and database/sql/driver packages are designed for using databases from Go and implementing database drivers, respectively.
See the design goals doc:
> http://golang.org/src/pkg/database/sql/doc.txt
# Drivers
Drivers for Go's sql package include:
* **MySQL**: https://github.com/ziutek/mymysql ` [*] `
* **MySQL**: https://github.com/go-sql-driver/mysql/ ` [*] `
* **Postgres** (pure Go): https://github.com/lib/pq ` [*] `
* **SQLite**: https://github.com/mattn/go-sqlite3 ` [*] `
* **DB2**: https://bitbucket.org/phiggins/db2cli
* **MS ADODB**: https://github.com/mattn/go-adodb
* **ODBC**: https://bitbucket.org/miquella/mgodbc
* **ODBC**: https://code.google.com/p/odbc
* **Oracle**: https://github.com/mattn/go-oci8
* **Postgres** (uses cgo): https://github.com/jbarham/gopgsqldriver
* **QL**: http://godoc.org/github.com/cznic/ql/driver
* **SQLite**: https://github.com/mxk/go-sqlite
* **Sybase SQL Anywhere**: https://github.com/a-palchikov/sqlago
* **MS SQL Server** (pure go): https://github.com/denisenkom/go-mssqldb
* **Firebird SQL**: https://github.com/nakagami/firebirdsql
Drivers marked with a ` [*] ` are both included in and pass the compatibility test suite at https://github.com/bradfitz/go-sql-test

123
SQLInterface.md Normal file

@ -0,0 +1,123 @@
# Introduction
The database/sql package provides a generic interface around SQL (or SQL-like) databases. See the [official documentation](http://golang.org/pkg/database/sql/) for details.
This page provides example usage patterns.
# Database driver
The database/sql package must be used in conjunction with a database driver.
See http://golang.org/s/sqldrivers for a list of drivers.
The documentation below assumes a driver has been imported.
# Connecting to a database
Open is used to create a database handle:
```
db, err := sql.Open(driver, dataSourceName)
```
Where driver specifies a database driver and dataSourceName
specifies database-specific connection information
such as database name and authentication credentials.
Note that Open does not directly open a database connection: this is deferred until a query is made. To verify that a connection can be made before making a query, use the Ping function.
After use, the database is closed using Close.
# Executing queries
Exec is used for queries where no rows are returned:
```
result, err := db.Exec(
"INSERT INTO users (name, age) VALUES (?, ?)",
"gopher",
27,
)
```
Where result contains the last insert ID and number of
rows affected. The availability of these values is dependent on
the database driver.
Query is used for retrieval:
```
rows, err := db.Query("SELECT name FROM users WHERE age = ?", age)
if err != nil {
log.Fatal(err)
}
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
log.Fatal(err)
}
fmt.Printf("%s is %d\n", name, age)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
```
QueryRow is used where only a single row is expected:
```
var age int64
row := db.QueryRow("SELECT age FROM users WHERE name = ?", name)
err := row.Scan(&age)
```
Prepared statements can be created with Prepare:
```
age := 27
stmt, err := db.Prepare("SELECT name FROM users WHERE age = ?")
if err != nil {
log.Fatal(err)
}
rows, err := stmt.Query(age)
// process rows
```
Exec, Query and QueryRow can be called on statements. After use, a
statement should be closed with Close.
# Transactions
Transactions are started with Begin:
```
tx, err := db.Begin()
if err != nil {
log.Fatal(err)
}
```
The Exec, Query, QueryRow and Prepare functions already covered can be
used in a transaction.
A transaction must end with a call to Commit or Rollback.
# Dealing with NULL
If a database column is nullable, one of the types supporting null values should be passed to Scan.
For example, if the name column in the names table is nullable:
```
var name NullString
err := db.QueryRow("SELECT name FROM names WHERE id = ?", id).Scan(&name)
...
if name.Valid {
// use name.String
} else {
// value is NULL
}
```
Only NullBool, NullFloat64, NullInt64 and NullString are implemented in
database/sql. Implementations of database-specific null types are left
to the database driver.

9
Screencasts.md Normal file

@ -0,0 +1,9 @@
# Screencasts
## Writing, building, installing, and testing Go code
A first stop for newcomers to the Go Programming Language.
This screencast describes setting up a workspace (GOPATH), writing commands and packages, using the go tool to build and install, and using the testing package to write unit tests.
[[video](http://www.youtube.com/watch?v=XCsL89YtqCs)]

69
SendingMail.md Normal file

@ -0,0 +1,69 @@
# Sending Mail
See also: http://golang.org/pkg/net/smtp/
Streaming the body:
```
package main
import (
"bytes"
"log"
"net/smtp"
)
func main() {
// Connect to the remote SMTP server.
c, err := smtp.Dial("mail.example.com:25")
if err != nil {
log.Fatal(err)
}
// Set the sender and recipient.
c.Mail("sender@example.org")
c.Rcpt("recipient@example.net")
// Send the email body.
wc, err := c.Data()
if err != nil {
log.Fatal(err)
}
defer wc.Close()
buf := bytes.NewBufferString("This is the email body.")
if _, err = buf.WriteTo(wc); err != nil {
log.Fatal(err)
}
}
```
Authenticated SMTP:
```
package main
import (
"log"
"net/smtp"
)
func main() {
// Set up authentication information.
auth := smtp.PlainAuth(
"",
"user@example.com",
"password",
"mail.example.com",
)
// Connect to the server, authenticate, set the sender and recipient,
// and send the email all in one step.
err := smtp.SendMail(
"mail.example.com:25",
auth,
"sender@example.org",
[]string{"recipient@example.net"},
[]byte("This is the email body."),
)
if err != nil {
log.Fatal(err)
}
}
```

28
SignalHandling.md Normal file

@ -0,0 +1,28 @@
# Introduction
Sometimes an application needs to save internal state or perform some cleanup activity before it exits, or needs to be able to reload a configuration file or write a memory/cpu profile on demand. In UNIX-like operating systems, signals can accomplish these tasks.
# Example
The following code demonstrates a program that waits for an interrupt signal and removes a temporary file when it occurs.
```
package main
import (
"io/ioutil"
"os"
"os/signal"
)
func main() {
f, err := ioutil.TempFile("", "test")
if err != nil {
panic(err)
}
defer os.Remove(f.Name())
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
<-sig
}
```

18
SimultaneousAssignment.md Normal file

@ -0,0 +1,18 @@
# Simultaneous Assignment
Simultaneous assignment is useful in many cases to make related assignments in a single statement. Sometimes they are required, either because only a single statement is available (e.g. in an if statement) or because the values will change after the statement (e.g. in the case of swap). All values on the right-hand side of the assignment operator are evaluated before the assignment is performed.
Simultaneous assignment in an if statement can improve readability, especially in test functions:
```
if got, want := someFunction(...), currTest.Expected; got != want {
t.Errorf("%d. someFunction(...) = %v, want %v", currIdx, got, want)
}
```
Swapping two values is also made simple using simultaneous assignment:
```
i, j = j, i
```
http://golang.org/ref/spec#Assignments

96
SliceTricks.md Normal file

@ -0,0 +1,96 @@
Since the introduction of the ` append ` built-in, most of the functionality of the ` container/vector ` package, which was removed in Go 1, can be replicated using ` append ` and ` copy `.
Here are the vector methods and their slice-manipulation analogues:
` AppendVector `
```
a = append(a, b...)
```
` Copy `
```
b = make([]T, len(a))
copy(b, a)
// or
b = append([]T(nil), a...)
```
` Cut `
```
a = append(a[:i], a[j:]...)
```
` Delete `
```
a = append(a[:i], a[i+1:]...)
// or
a = a[:i+copy(a[i:], a[i+1:])]
```
` Delete without preserving order `
```
a[i], a = a[len(a)-1], a[:len(a)-1]
```
**NOTE** If the type of the element is a _pointer_ or a struct with pointer fields, which need to be garbage collected, the above implementations of ` Cut ` and ` Delete ` have a potential _memory leak_ problem: some elements with values are still referenced by slice ` a ` and thus can not be collected. The following code can fix this problem:
> ` Cut `
```
copy(a[i:], a[j:])
for k, n := len(a)-j+i, len(a); k < n; k ++ {
a[k] = nil // or the zero value of T
} // for k
a = a[:len(a)-j+i]
```
> ` Delete `
```
copy(a[i:], a[i+1:])
a[len(a)-1] = nil // or the zero value of T
a = a[:len(a)-1]
```
> ` Delete without preserving order `
```
a[i], a[len(a)-1], a = a[len(a)-1], nil, a[:len(a)-1]
```
` Expand `
```
a = append(a[:i], append(make([]T, j), a[i:]...)...)
```
` Extend `
```
a = append(a, make([]T, j)...)
```
` Insert `
```
a = append(a[:i], append([]T{x}, a[i:]...)...)
```
**NOTE** The second ` append ` creates a new slice with its own underlying storage and copies elements in ` a[i:] ` to that slice, and these elements are then copied back to slice ` a ` (by the first ` append `). The creation of the new slice (and thus memory garbage) and the second copy can be avoided by using an alternative way:
> ` Insert `
```
s = append(s, 0)
copy(s[i+1:], s[i:])
s[i] = x
```
` InsertVector `
```
a = append(a[:i], append(b, a[i:]...)...)
```
` Pop `
```
x, a = a[len(a)-1], a[:len(a)-1]
```
` Push `
```
a = append(a, x)
```
## Additional Tricks
### Filtering without allocating
This trick uses the fact that a slice shares the same backing array and capacity as the original, so the storage is reused for the filtered slice. Of course, the original contents are modified.
```
b := a[:0]
for _, x := range a {
if f(x) {
b = append(b, x)
}
}
```

1
Style.md Normal file

@ -0,0 +1 @@
See CodeReviewComments.

28
SubRepositories.md Normal file

@ -0,0 +1,28 @@
These packages are part of the Go Project but outside the main Go tree.
They are developed under looser [compatibility requirements](http://golang.org/doc/go1compat.html) than the Go core.
Install them with "go get".
* [[docs](http://godoc.org/golang.org/x/tools)] [[source](https://code.google.com/p/go/source/browse/?repo=tools)] ` golang.org/x/tools ` — godoc, vet, cover, and other tools.
* [[docs](http://godoc.org/golang.org/x/mobile)] [[source](https://code.google.com/p/go/source/browse/?repo=mobile)] ` golang.org/x/mobile ` — libraries and build tools for Go on Android.
* [[docs](http://godoc.org/golang.org/x/crypto)] [[source](https://code.google.com/p/go/source/browse/?repo=crypto)] ` golang.org/x/crypto ` — additional cryptography packages.
* [[docs](http://godoc.org/golang.org/x/image)] [[source](https://code.google.com/p/go/source/browse/?repo=image)] ` golang.org/x/image ` — additional imaging packages.
* [[docs](http://godoc.org/golang.org/x/net)] [[source](https://code.google.com/p/go/source/browse/?repo=net)] ` golang.org/x/net ` — additional networking packages.
* [[docs](http://godoc.org/golang.org/x/sys)] [[source](https://code.google.com/p/go/source/browse/?repo=sys)] ` golang.org/x/sys ` — for low-level interactions with the operating system.
* [[docs](http://godoc.org/golang.org/x/text)] [[source](https://code.google.com/p/go/source/browse/?repo=text)] ` golang.org/x/text ` — packages for working with text.
* [[docs](http://godoc.org/golang.org/x/blog)] [[source](https://code.google.com/p/go/source/browse/?repo=blog)] ` golang.org/x/blog ` — the content and server program for [blog.golang.org](http://blog.golang.org).
* [[docs](http://godoc.org/golang.org/x/talks)] [[source](https://code.google.com/p/go/source/browse/?repo=talks)] ` golang.org/x/talks ` — the content and server program for [talks.golang.org](http://talks.golang.org).
* [[docs](http://godoc.org/golang.org/x/codereview)] [[source](https://code.google.com/p/go/source/browse/?repo=codereview)] ` golang.org/x/codereview ` — tools for code review.
* [[docs](http://godoc.org/golang.org/x/benchmarks)] [[source](https://code.google.com/p/go/source/browse/?repo=benchmarks)] ` golang.org/x/benchmarks `
* [[docs](http://godoc.org/golang.org/x/exp)] [[source](https://code.google.com/p/go/source/browse/?repo=exp)] ` golang.org/x/exp ` — experimental code (handle with care).
[List of all packages in sub-repositories](http://godoc.org/-/subrepo)
NOTE: On 9 November 2014, Go sub-repositories moved to [new import paths](https://groups.google.com/forum/#!msg/golang-nuts/eD8dh3T9yyA/l5Ail-xfMiAJ).

37
SuccessStories.md Normal file

@ -0,0 +1,37 @@
# Go success stories from around the web
* [The Reliability of Go](http://andrewwdeane.blogspot.de/2013/05/the-reliability-of-go.html)
* [A Go Redirection Service](http://blog.dnsimple.com/a-golang-redirection-service/)
* [pool.ntp.org DNS server in Go](http://news.ntppool.org/2012/10/new-dns-server.html)
* [Juju at Canonical](http://www.reddit.com/r/programming/comments/18atce/juju_canonical_109k_lines_of_go_code/)
* [Go at bitly](http://word.bitly.com/post/29550171827/go-go-gadget)
* [NSQ: realtime distributed message processing at scale](http://word.bitly.com/post/33232969144/nsq)
* [CloudFlare blows hole in laws of Web physics with Go and Railgun](http://arstechnica.com/information-technology/2013/02/cloudflare-blows-hole-in-laws-of-web-physics-with-go-and-railgun/)
* [Go as an alternative to Node.js for Very Fast Servers](http://techblog.safaribooksonline.com/2013/02/22/go-as-an-alternative-to-node-js-for-very-fast-servers/)
* [Why I Like Go](https://gist.github.com/freeformz/4746274)
* [Why I Program in Go](http://tech.t9i.in/2013/01/why-program-in-go/)
* [dl.google.com now served by Go](https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/BNUNbKSypE0)
* [Google's Go Programming Language Grows Up: Now What?](http://www.readwriteweb.com/cloud/2012/03/googles-go-programming-languag.php)
* [Moving to Go](http://blog.toggl.com/2012/09/moving-to-go/)
* [Rob Pike: Why Learn Go?](http://www.youtube.com/watch?v=FTl0tl9BGdc)
* [Go At Conformal](https://www.cyphertite.com/blog.php?/archives/7-Go-at-Conformal..html)
* [Why I went from Python to Go (and not node.js)](http://jordanorelli.tumblr.com/post/31533769172/why-i-went-from-python-to-go-and-not-node-js)
* [Another go at the Next Big Language](http://dave.cheney.net/2012/09/03/another-go-at-the-next-big-language)
* [@tobi](http://twitter.com/tobi): ["I have now completed two projects in Go. I predict that it's going to be the dominant language for server work."](https://twitter.com/tobi/status/245873677483274240)
* [@derekcollison](http://twitter.com/derekcollison): ["Prediction: Go will become the dominant language for systems work in IaaS, Orchestration, and PaaS in 24 months."](https://twitter.com/derekcollison/status/245522124666716160)
* [Will Go be the new go-to programming language?](http://gigaom.com/cloud/will-go-be-the-new-go-to-programming-language/)
* [PARALLELISM FOR THE WIN!](http://areyoufuckingcoding.me/2012/08/16/parallelism-for-the-win/)
* [Go is boring](http://aeronotix.pl/blog/go-is-boring)
* [Dr. Dobb's: Why Not Go?](http://www.drdobbs.com/open-source/why-not-go/240005062)
* [Google I/O 2012: Go in production](http://www.youtube.com/watch?v=kKQLhGZVN4A)
* [Go at Novartis](https://plus.google.com/114945221884326152379/posts/d1SVaqkRyTL)
* [Go at the BBC](http://www.quora.com/Go-programming-language/Is-Google-Go-ready-for-production-use/answer/Kunal-Anand)
* [Go at SoundCloud](http://backstage.soundcloud.com/2012/07/go-at-soundcloud/)
* [Go at Moovweb](https://groups.google.com/forum/#!topic/golang-nuts/MeiTNnGhLg8/discussion)
* [Building StatHat with Go](http://blog.golang.org/2011/12/building-stathat-with-go.html)
* [Go at CloudFlare](http://blog.cloudflare.com/go-at-cloudflare)
* [Why you PHP guys should learn Golang](http://www.mikespook.com/2012/08/why-you-php-guys-should-learn-golang/)
* [I/O BootCamp 2011: Real World Go](http://www.youtube.com/watch?v=7QDVRowyUQA)
* [Go at Heroku](http://blog.golang.org/2011/04/go-at-heroku.html)
See also [GoUsers](wiki/GoUsers)

186
Switch.md Normal file

@ -0,0 +1,186 @@
# Switch
Spec: http://golang.org/doc/go_spec.html#Switch_statements
Go's ` switch ` statements are pretty neat. For one thing, you don't need to break at the end of each case.
```
switch c {
case '&':
esc = "&amp;"
case '\'':
esc = "&apos;"
case '<':
esc = "&lt;"
case '>':
esc = "&gt;"
case '"':
esc = "&quot;"
default:
panic("unrecognized escape character")
}
```
[src/pkg/html/escape.go](http://golang.org/src/pkg/html/escape.go#L178)
## Not just integers
Switches work on values of any type.
```
switch syscall.OS {
case "windows":
sd = &sysDir{
Getenv("SystemRoot") + `\system32\drivers\etc`,
[]string{
"hosts",
"networks",
"protocol",
"services",
},
}
case "plan9":
sd = &sysDir{
"/lib/ndb",
[]string{
"common",
"local",
},
}
default:
sd = &sysDir{
"/etc",
[]string{
"group",
"hosts",
"passwd",
},
}
}
```
## Missing expression
In fact, you don't need to switch on anything at all. A switch with no value means "switch true", making it a cleaner version of an if-else chain, as in this example from Effective Go:
```
func unhex(c byte) byte {
switch {
case '0' <= c && c <= '9':
return c - '0'
case 'a' <= c && c <= 'f':
return c - 'a' + 10
case 'A' <= c && c <= 'F':
return c - 'A' + 10
}
return 0
}
```
## Break
Go's ` switch ` statements ` break ` implicitly, but ` break ` is still useful:
```
command := ReadCommand()
argv := strings.Fields(command)
switch argv[0] {
case "echo":
fmt.Print(argv[1:]...)
case "cat":
if len(argv) <= 1 {
fmt.Println("Usage: cat <filename>")
break
}
PrintFile(argv[1])
default:
fmt.Println("Unknown command; try 'echo' or 'cat'")
}
```
## Fall through
To fall through to a subsequent case, use the ` fallthrough ` keyword:
```
// Unpack 4 bytes into uint32 to repack into base 85 5-byte.
var v uint32
switch len(src) {
default:
v |= uint32(src[3])
fallthrough
case 3:
v |= uint32(src[2]) << 8
fallthrough
case 2:
v |= uint32(src[1]) << 16
fallthrough
case 1:
v |= uint32(src[0]) << 24
}
```
[src/pkg/encoding/ascii85/ascii85.go](http://golang.org/src/pkg/encoding/ascii85/ascii85.go#L43)
The 'fallthrough' must be the last thing in the case; you can't write something like
```
switch {
case f():
if g() {
fallthrough // Does not work!
}
h()
default:
error()
}
```
## Multiple cases
If you want to use multiple values in the same case, use a comma-separated list.
```
func letterOp(code int) bool {
switch chars[code].category {
case "Lu", "Ll", "Lt", "Lm", "Lo":
return true
}
return false
}
```
## Type switch
With a type switch you can switch on the type of an interface value (only):
```
func typeName(v interface{}) string {
switch v.(type) {
case int:
return "int"
case string:
return "string"
default:
return "unknown"
}
panic("unreachable")
}
```
You can also declare a variable and it will have the type of each ` case `:
```
func do(v interface{}) string {
switch u := v.(type) {
case int:
return strconv.Itoa(u*2) // u has type int
case string:
mid := len(u) / 2 // split - u has type string
return u[mid:] + u[:mid] // join
}
return "unknown"
}
do(21) == "42"
do("bitrab") == "rabbit"
do(3.142) == "unknown"
```

49
TableDrivenTests.md Normal file

@ -0,0 +1,49 @@
# Introduction
Writing good tests is not trivial, but in many situations a lot of ground can be covered with table-driven tests: Each table entry is a complete test case with inputs and expected results, and sometimes with additional information such as a test name to make the test output easily readable. If you ever find yourself using copy and paste when writing a test, think about whether refactoring into a table-driven test or pulling the copied code out into a helper function might be a better option.
Given a table of test cases, the actual test simply iterates through all table entries and for each entry performs the necessary tests. The test code is written once and amortized over all table entries, so it makes sense to write a careful test with good error messages.
## Example of a table driven test
Here is a good example from the testing code for the ` fmt ` package ( http://golang.org/pkg/fmt/ ):
```
var flagtests = []struct {
in string
out string
}{
{"%a", "[%a]"},
{"%-a", "[%-a]"},
{"%+a", "[%+a]"},
{"%#a", "[%#a]"},
{"% a", "[% a]"},
{"%0a", "[%0a]"},
{"%1.2a", "[%1.2a]"},
{"%-1.2a", "[%-1.2a]"},
{"%+1.2a", "[%+1.2a]"},
{"%-+1.2a", "[%+-1.2a]"},
{"%-+1.2abc", "[%+-1.2a]bc"},
{"%-1.2abc", "[%-1.2a]bc"},
}
func TestFlagParser(t *testing.T) {
var flagprinter flagPrinter
for _, tt := range flagtests {
s := Sprintf(tt.in, &flagprinter)
if s != tt.out {
t.Errorf("Sprintf(%q, &flagprinter) => %q, want %q", tt.in, s, tt.out)
}
}
}
```
Note the detailed error message provided with ` t.Errorf `: The name of the function tested, its inputs, result, and expected result are provided. When the test fails it is immediately obvious which test failed and why, even without having to read the test code.
A ` t.Errorf ` call is not an assertion. The test continues even after an error is logged. For example, when testing something with integer input, it is worth knowing that the function fails for all inputs, or only for odd inputs, or for powers of two.
## References
* http://golang.org/doc/code.html#Testing
* http://golang.org/doc/faq#assertions
* http://golang.org/doc/faq#testing_framework
* http://golang.org/pkg/testing/

25
Timeouts.md Normal file

@ -0,0 +1,25 @@
# Timeouts and Deadlines
To abandon synchronous calls that run too long, use the select statement with time.After:
```
import "time"
c := make(chan error, 1)
go func() { c <- client.Call("Service.Method", args, &reply) } ()
select {
case err := <-c:
// use err and reply
case <-time.After(timeoutNanoseconds):
// call timed out
}
```
Note that the channel ` c ` has a buffer size of 1. If it were an unbuffered channel and the client.Call method took more than ` timeoutNanoseconds `, the channel send would block forever and the goroutine would never be destroyed.
## References
time.After: http://golang.org/pkg/time/#After
select: http://golang.org/doc/go_spec.html#Select_statements
blog post: http://blog.golang.org/2010/09/go-concurrency-patterns-timing-out-and.html

26
Ubuntu.md Normal file

@ -0,0 +1,26 @@
## Install package ` golang `
The ` golang ` Debian package may have already made its way into your Ubuntu distribution. Try this:
```
sudo apt-get install golang
```
## If that didn't work
If you have an arm, i386, or amd64, with the Ubuntu Lucid, Maverick,
Natty, Oneiric, or Precise release, you can easily install Go 1 right
now as a package by running:
```
sudo add-apt-repository ppa:gophers/go
sudo apt-get update
sudo apt-get install golang-stable
```
(If you don't have ` add-apt-repository `, run "` sudo apt-get install python-software-properties `".)
The ` golang-stable ` package includes everything necessary for developing
with Go. There are also ` golang-tip ` and ` golang-weekly ` packages in the
same repository, and these are up-to-date, except ` golang-weekly ` isn't
really interesting at the moment since golang-stable is more recent.

85
WindowsBuild.md Normal file

@ -0,0 +1,85 @@
# Use [winstrap](https://code.google.com/p/winstrap)
Download [winstrap.exe](http://storage.googleapis.com/winstrap/winstrap-20140711.exe) and run it.
It will download some installers to your desktop, which you should run. Just click through; all the defaults are fine.
Then it will check out Go and place it in c:\Users\%USER%\goroot and build it.
That's it.
---
Older (deprecated?) instructions follow.
---
# Install MinGW/MSYS
Download and save the latest version of the automated MinGW installer executable (` exe `) file from SourceForge.
http://sourceforge.net/projects/mingw/files/Automated%20MinGW%20Installer/mingw-get-inst/
Open and run the saved automated MinGW installer executable file, which is named ` mingw-get-inst-yyyymmdd.exe `, where ` yyyymmdd ` is the version date stamp. For example, ` mingw-get-inst-20110530.exe `.
The MinGW Setup Wizard window will open with the title "Setup - MinGW-Get". Except for the following, accept the setup defaults, unless it's necessary to change them.
For Repository Catalogues, check the Download latest repository catalogues button.
For Select Components, the MinGW Compiler Suite, the C Compiler box is automatically checked. Scroll down to the bottom of the list and check the MinGW Developer Toolkit box, which includes the MSYS Basic System.
For Ready to Install, review and verify the installation settings, which should look similar this:
```
Installing:
mingw-get
pkginfo
C Compiler
MSYS Basic System
MinGW Developer Toolkit
Downloading latest repository catalogues
Destination location:
C:\MinGW
```
When the installation settings are correct, Install.
The installation loads the package installation catalogues and downloads and installs the files. The installation may take some time, largely depending on the download speed.
The MSYS terminal window may be opened by opening and running the ` C:\MinGW\msys\1.0\msys.bat ` batch file.
# Build
```
hg clone https://code.google.com/p/go/
cd go\src
all.bat
```
# 64-bit Notes
1. Ensure you are able to compile a working 32-bit Go first.
1. Grab the latest zip from http://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win64/Automated%20Builds/ and extract it over the MinGW directory, so that for example the .exe files end up in the same location as the 32-bit ones.
1. Replace ` gcc.exe ` and ` ar.exe ` with their 64-bit counterparts.
1. Set ` GOARCH=amd64 ` and away you go!
# Alternative Strategy
Install http://tdm-gcc.tdragon.net/
Install Python 2.x.
Install Mercurial for Python 2.x.
Make a "godev.bat" file on your desktop with:
```
set GOROOT=c:\go
set GOPATH=c:\you\gopath
set PATH=%PATH%;%GOROOT%\bin;C:\Python27;C:\Python27\Scripts
cd %GOROOT%\src
CMD
```
Then double-click and type "all.bat". The codereview extension should work too (test with "hg pq")

71
WindowsCrossCompiling.md Normal file

@ -0,0 +1,71 @@
# Building windows go programs on linux
I use linux/386, but, I suspect, this procedure will apply to other host platforms as well.
First step is to build host version of go:
```
$ cd $GOROOT/src
$ ./make.bash
```
Next you need to build the rest of go compilers and linkers. I have small program to do that:
```
$ cat ~/bin/buildcmd
#!/bin/sh
set -e
for arch in 8 6; do
for cmd in a c g l; do
go tool dist install -v cmd/$arch$cmd
done
done
exit 0
```
Last step is to build windows versions of standard commands and libraries. I have small script for that too:
```
$ cat ~/bin/buildpkg
#!/bin/sh
if [ -z "$1" ]; then
echo 'GOOS is not specified' 1>&2
exit 2
else
export GOOS=$1
if [ "$GOOS" = "windows" ]; then
export CGO_ENABLED=0
fi
fi
shift
if [ -n "$1" ]; then
export GOARCH=$1
fi
cd $GOROOT/src
go tool dist install -v pkg/runtime
go install -v -a std
```
I run it like that:
```
$ ~/bin/buildpkg windows 386
```
to build windows/386 version of Go commands and packages. You can, probably, see it from my script, I exclude building of any cgo related parts - these will not work for me, since I do not have correspondent gcc cross-compiling tools installed. So I just skip those.
Now we're ready to build our windows executable:
```
$ cat hello.go
package main
import "fmt"
func main() {
fmt.Printf("Hello\n")
}
$ GOOS=windows GOARCH=386 go build -o hello.exe hello.go
```
We just need to find Windows computer to run our hello.exe.

136
WindowsDLLs.md Normal file

@ -0,0 +1,136 @@
# Calling a Windows DLL
There are a few ways to call "C" code from inside Go
First way: Dynamically load a dll, then call a method on it. You can call the method via "syscallXX" (the XX is number of parameters, but if it has few than that, like if you need seven parameter, then syscall9 will still work, you just tell it the number of arguments is 7). This way also works with Linux shared libraries, as well, if you're targeting linux:
A sample program that calls Windows DLLs from Go:
```
package main
import (
"fmt"
"syscall"
"unsafe"
)
func abort(funcname string, err error) {
panic(fmt.Sprintf("%s failed: %v", funcname, err))
}
var (
kernel32, _ = syscall.LoadLibrary("kernel32.dll")
getModuleHandle, _ = syscall.GetProcAddress(kernel32, "GetModuleHandleW")
user32, _ = syscall.LoadLibrary("user32.dll")
messageBox, _ = syscall.GetProcAddress(user32, "MessageBoxW")
)
const (
MB_OK = 0x00000000
MB_OKCANCEL = 0x00000001
MB_ABORTRETRYIGNORE = 0x00000002
MB_YESNOCANCEL = 0x00000003
MB_YESNO = 0x00000004
MB_RETRYCANCEL = 0x00000005
MB_CANCELTRYCONTINUE = 0x00000006
MB_ICONHAND = 0x00000010
MB_ICONQUESTION = 0x00000020
MB_ICONEXCLAMATION = 0x00000030
MB_ICONASTERISK = 0x00000040
MB_USERICON = 0x00000080
MB_ICONWARNING = MB_ICONEXCLAMATION
MB_ICONERROR = MB_ICONHAND
MB_ICONINFORMATION = MB_ICONASTERISK
MB_ICONSTOP = MB_ICONHAND
MB_DEFBUTTON1 = 0x00000000
MB_DEFBUTTON2 = 0x00000100
MB_DEFBUTTON3 = 0x00000200
MB_DEFBUTTON4 = 0x00000300
)
func MessageBox(caption, text string, style uintptr) (result int) {
var nargs uintptr = 4
ret, _, callErr := syscall.Syscall9(uintptr(messageBox),
nargs,
0,
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(text))),
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(caption))),
style,
0,
0,
0,
0,
0)
if callErr != 0 {
abort("Call MessageBox", callErr)
}
result = int(ret)
return
}
func GetModuleHandle() (handle uintptr) {
var nargs uintptr = 0
if ret, _, callErr := syscall.Syscall(uintptr(getModuleHandle), nargs, 0, 0, 0); callErr != 0 {
abort("Call GetModuleHandle", callErr)
} else {
handle = ret
}
return
}
func main() {
defer syscall.FreeLibrary(kernel32)
defer syscall.FreeLibrary(user32)
fmt.Printf("Return: %d\n", MessageBox("Done Title", "This test is Done.", MB_YESNOCANCEL))
}
func init() {
fmt.Print("Starting Up\n")
}
```
Second way is via syscall.NewProc (etc.) instead of syscall.GetProcAddress. These are basically some helper methods over the syscall ones, you saw above, and are available in Windows only: http://golang.org/src/pkg/syscall/dll_windows.go
```
package main
import (
"syscall"
"unsafe"
"fmt"
)
func main() {
var mod = syscall.NewLazyDLL("user32.dll")
var proc = mod.NewProc("MessageBoxW");
var MB_YESNOCANCEL = 0x00000003
ret, _, _ := proc.Call(0,
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("Done Title"))),
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("This test is Done."))),
uintptr(MB_YESNOCANCEL));
fmt.Printf("Return: %d\n", ret)
}
```
A third way would be to call into libraries basically by "linking" against the library, using the "[cgo](wiki/cgo)" method (this way works in Linux and Windows):
This way would look something like this
```
import ("C")
...
C.MessageBoxW(...)
```
See [cgo](wiki/cgo) for further details.

5
WindowsSupport.md Normal file

@ -0,0 +1,5 @@
# Go under MS Windows
The windows port is stable and officially supported.
* See the [open Windows issues](http://code.google.com/p/go/issues/list?q=label:os-windows) on the issue tracker.

313
cgo.md Normal file

@ -0,0 +1,313 @@
# Introduction
First, http://golang.org/cmd/cgo is the primary cgo documentation.
There is also a good introduction article at http://golang.org/doc/articles/c_go_cgo.html.
## The basics
If a Go source file imports ` "C" `, it is using cgo. The Go file will have access to anything appearing in the comment immediately preceding the line ` import "C" `, and will be linked against all other cgo comments in other Go files, and all C files included in the build process.
Note that there must be no blank lines in between the cgo comment and the import statement.
To access a symbol originating from the C side, use the package name ` C `. That is, if you want to call the C function ` printf() ` from Go code, you write ` C.printf() `. Since variable argument methods like printf aren't supported yet (issue [975](https://code.google.com/p/go/issues/detail?id=975)), we will wrap it in the C method "myprint":
```
package cgoexample
/*
#include <stdio.h>
#include <stdlib.h>
void myprint(char* s) {
printf("%s", s);
}
*/
import "C"
import "unsafe"
func Example() {
cs := C.CString("Hello from stdio\n")
C.myprint(cs)
C.free(unsafe.Pointer(cs))
}
```
## Calling Go functions from C
It is possible to call both top-level Go functions and function variables from C code invoked from Go code using cgo.
### Global functions
Go makes its functions available to C code through use of a special ` //export ` comment.
Note: you can't define any C functions in preamble if you're using exports.
For example, there are two files, foo.c and foo.go:
foo.go contains:
```
package gocallback
import "fmt"
/*
#include <stdio.h>
extern void ACFunction();
*/
import "C"
//export AGoFunction
func AGoFunction() {
fmt.Println("AGoFunction()")
}
func Example() {
C.ACFunction()
}
```
foo.c contains:
```
#include "_cgo_export.h"
void ACFunction() {
printf("ACFunction()\n");
AGoFunction();
}
```
### Function variables
The following code shows an example of invoking a Go callback from C code. Go passes the function variable to the CGo code by calling ` CallMyFunction() `. ` CallMyFunction() ` invokes the callback by sending it back into the Go code, with the desired parameters, for unpacking and calling.
```
package gocallback
import (
"unsafe"
"fmt"
)
/*
extern void go_callback_int(void* foo, int p1);
// normally you will have to define function or variables
// in another separate C file to avoid the multiple definition
// errors, however, using "static inline" is a nice workaround
// for simple functions like this one.
static inline void CallMyFunction(void* pfoo) {
go_callback_int(pfoo, 5);
}
*/
import "C"
//export go_callback_int
func go_callback_int(pfoo unsafe.Pointer, p1 C.int) {
foo := *(*func(C.int))(pfoo)
foo(p1)
}
func MyCallback(x C.int) {
fmt.Println("callback with", x)
}
// we store it in a global variable so that the garbage collector
// doesn't clean up the memory for any temporary variables created.
var MyCallbackFunc = MyCallback
func Example() {
C.CallMyFunction(unsafe.Pointer(&MyCallbackFunc))
}
```
### Function pointer callbacks
C code can call exported Go functions with their explicit name. But if a C-program wants a function pointer, a gateway function has to be written. This is because we can't take the address of a Go function and give that to C-code since the cgo tool will generate a stub in C that should be called. The following example shows how to integrate with C code wanting a function pointer of a give type.
Place these source files under _$GOPATH/src/ccallbacks/_. Compile and run with:
```
$ gcc -c clibrary.c
$ ar cru libclibrary.a clibrary.o
$ go build ccallbacks
$ ./ccallbacks
Go.main(): calling C function with callback to us
C.some_c_func(): calling callback with arg = 2
C.callOnMeGo_cgo(): called with arg = 2
Go.callOnMeGo(): called with arg = 2
C.some_c_func(): callback responded with 3
```
**goprog.go**
```
package main
/*
#cgo CFLAGS: -I .
#cgo LDFLAGS: -L . -lclibrary
#include "clibrary.h"
int callOnMeGo_cgo(int in); // Forward declaration.
*/
import "C"
import (
"fmt"
"unsafe"
)
//export callOnMeGo
func callOnMeGo(in int) int {
fmt.Printf("Go.callOnMeGo(): called with arg = %d\n", in)
return in + 1
}
func main() {
fmt.Printf("Go.main(): calling C function with callback to us\n")
C.some_c_func((C.callback_fcn)(unsafe.Pointer(C.callOnMeGo_cgo)))
}
```
**cfuncs.go**
```
package main
/*
#include <stdio.h>
// The gateway function
int callOnMeGo_cgo(int in)
{
printf("C.callOnMeGo_cgo(): called with arg = %d\n", in);
return callOnMeGo(in);
}
*/
import "C"
```
**clibrary.h**
```
#ifndef CLIBRARY_H
#define CLIBRARY_H
typedef int (*callback_fcn)(int);
void some_c_func(callback_fcn);
#endif
```
**clibrary.c**
```
#include <stdio.h>
#include "clibrary.h"
void some_c_func(callback_fcn callback)
{
int arg = 2;
printf("C.some_c_func(): calling callback with arg = %d\n", arg);
int response = callback(2);
printf("C.some_c_func(): callback responded with %d\n", response);
}
```
## Go strings and C strings
Go strings and C strings are different. Go strings are the combination of a length and a pointer to the first character in the string. C strings are just the pointer to the first character, and are terminated by the first instance of the null character, ` '\0' `.
Go provides means to go from one to another in the form of the following three functions:
* ` func C.CString(goString string) *C.char `
* ` func C.GoString(cString *C.char) string `
* ` func C.GoStringN(cString *C.char, length C.int) string `
One important thing to remember is that ` C.CString() ` will allocate a new string of the appropriate length, and return it. That means the C string is not going to be garbage collected and it is up to **you** to free it. A standard way to do this follows.
```
// #include <stdlib.h>
import "C"
import "unsafe"
...
var cmsg *C.char = C.CString("hi")
defer C.free(unsafe.Pointer(cmsg))
// do something with the C string
```
Of course, you aren't required to use ` defer ` to call ` C.free() `. You can free the C string whenever you like, but it is your responsibility to make sure it happens.
## Turning C arrays into Go slices
C arrays are typically either null-terminated or have a length kept elsewhere.
Go provides the following function to make a new Go byte slice from a C array:
* ` func C.GoBytes(cArray unsafe.Pointer, length C.int) []byte `
To create a Go slice backed by a C array (without copying the original data), one needs to acquire this length at runtime and use ` reflect.SliceHeader `.
```
import "C"
import "unsafe"
...
var theCArray *C.YourType = C.getTheArray()
length := int(C.getTheArrayLength())
hdr := reflect.SliceHeader{
Data: uintptr(unsafe.Pointer(theCArray)),
Len: length,
Cap: length,
}
goSlice := *(*[]C.YourType)(unsafe.Pointer(&hdr))
// now goSlice is a Go slice backed by the C array
```
It is important to keep in mind that the Go garbage collector will not interact with this data, and that if it is freed from the C side of things, the behavior of any Go code using the slice is nondeterministic.
Another simpler solution is casting the pointer to a pointer to a very big array and then
slice it to the length that you want (also remember to set the cap if you're using Go 1.2
or later), for example (see http://play.golang.org/p/XuC0xqtAIC for a runnable example):
```
import "C"
import "unsafe"
...
var theCArray *C.YourType = C.getTheArray()
length := C.getTheArrayLength()
slice := (*[1 << 30]C.YourType)(unsafe.Pointer(theCArray))[:length:length]
```
## Common Pitfalls
### Struct Alignment Issues
As Go doesn't support packed struct (e.g., structs where maximum alignment is 1 byte), you can't
use packed C struct in Go. Even if you program passes compilation, it won't do what you want.
To use it, you have to read/write the struct as byte array/slice.
Another problem is that some types has lower alignment requirement than their counterpart in Go,
and if that type happens to be aligned in C but not in Go rules, that struct simply can't be represented
in Go. An example is this (issue 7560 (on Google Code)):
```
struct T {
uint32_t pad;
complex float x;
};
```
Go's complex64 has an alignment of 8-byte, where as C has only 4-byte (because C treats the
complex float internally as a ` struct { float real; float imag; } `, not a basic type), this T struct simply
doesn't have a Go representation. For this case, if you control the layout of the struct, move the
complex float so that it is also aligned to 8-byte is better, and if you're not willing to move it,
use this form will force it to align to 8-byte (and waste 4-byte):
```
struct T {
uint32_t pad;
__attribute__((align(8))) complex float x;
};
```
However, if you don't control the struct layout, you will have to define accessor C functions for
that struct because cgo won't be able to translate that struct into equivalent Go struct.
### ` //export ` and definition in preamble
If a Go source file uses any ` //export ` directives, then the C code in the comment may only include declarations (` extern int f(); `), not definitions (` int f() { return 1; } ` or ` int n; `).
Note: you can use ` static inline ` trick to work around this restriction for tiny functions defined
in the preamble (see above for a complete example).
### Windows
In order to use cgo on Windows, you'll also need to first install a gcc compiler (for instance, mingw-w64) and have gcc.exe (etc.) in your PATH environment variable before compiling with cgo will work.

182
heapdump13.md Normal file

@ -0,0 +1,182 @@
Heap dump format for other versions:
* [heapdump14](wiki/heapdump14)
# Introduction
Go 1.3 added a runtime/debug.WriteHeapDump function that writes all objects in the heap plus additional info (roots, goroutines, finalizers, etc.) to a file. The format of this file is specified here.
# Details
The file starts with the bytes of the string "go1.3 heap dump\n".
The rest of the file is a sequence of records. Records can be of several different kinds. Records will contain the following primitives:
* uvarint - a 64-bit unsigned integer encoded as in encoding/binary.{Put,Read}Uvarint
* string - a uvarint-encoded length followed by that many bytes of data
* bool - a uvarint-encoded 0 for false or 1 for true
* fieldlist - a description of the pointer-bearing portions of a memory region. It consists of repeated pairs of uvarints encoding a field kind and a field offset, followed by and end-of-list marker. The possible kinds are 1=Ptr, 2=String, 3=Slice, 4=Iface, and 5=Eface. 0=Eol is the end of list marker. The end of list marker does not have a corresponding offset.
Each record starts with a uvarint-encoded integer describing the type of the record:
* 0 = EOF
* 1 = object
* 2 = otherroot
* 3 = type
* 4 = goroutine
* 5 = stack frame
* 6 = dump params
* 7 = registered finalizer
* 8 = itab
* 9 = OS thread
* 10 = mem stats
* 11 = queued finalizer
* 12 = data segment
* 13 = bss segment
* 14 = defer record
* 15 = panic record
* 16 = alloc/free profile record
* 17 = alloc stack trace sample
The remaining fields of each record are type-dependent and are described below.
# EOF
An EOF record has no fields and must appear last.
# object
* uvarint: address of object
* uvarint: address of type descriptor (or 0 if unknown)
* uvarint: kind of object (0=regular 1=array 2=channel 127=conservatively scanned)
* string: contents of object
For array or channel kinds, the type must be nonzero.
The size of the contents string is the size of the containing sizeclass, not the size of the type itself. As such, contents size may be somewhat bigger than the type size. It may be a lot bigger for array and channel types. For instance, an array with n elements will have a content size bigger than or equal to n times the type size.
# otherroot
* string: textual description of where this root came from
* uvarint: root pointer
# type
* uvarint: address of type descriptor
* uvarint: size of an object of this type
* string: name of type
* bool: whether the data field of an interface containing a value of this type is a pointer
* fieldlist: a list of the kinds and locations of pointer-containing fields in objects of this type
# goroutine (G)
* uvarint: address of descriptor
* uvarint: pointer to the top of stack (the currently running frame, a.k.a. depth 0)
* uvarint: go routine ID
* uvarint: the location of the go statement that created this goroutine
* uvarint: status
* bool: is a Go routine started by the system
* bool: is a background Go routine
* uvarint: approximate time the go routine last started waiting (nanoseconds since the Epoch)
* string: textual reason why it is waiting
* uvarint: context pointer of currently running frame
* uvarint: address of os thread descriptor (M)
* uvarint: top defer record
* uvarint: top panic record
Possible statuses:
* 0 = idle
* 1 = runnable
* 3 = syscall
* 4 = waiting
The wait fields must be present in all cases, but they only mean something if the status is "waiting".
# stack frame
* uvarint: stack pointer (lowest address in frame)
* uvarint: depth in stack (0 = top of stack)
* uvarint: stack pointer of child frame (or 0 if none)
* string: contents of stack frame
* uvarint: entry pc for function
* uvarint: current pc for function
* uvarint: continuation pc for function (where function may resume, if anywhere)
* string: function name
* fieldlist: list of kind and offset of pointer-containing fields in this frame
# dump params
* bool: big endian
* uvarint: pointer size in bytes
* uvarint: channel header size in bytes
* uvarint: starting address of heap
* uvarint: ending address of heap
* uvarint: thechar = architecture specifier
* string: GOEXPERIMENT environment variable value
* uvarint: runtime.ncpu
# finalizer
* uvarint: address of object that has a finalizer
* uvarint: pointer to FuncVal describing the finalizer
* uvarint: PC of finalizer entry point
* uvarint: type of finalizer argument
* uvarint: type of object
This finalizer has been registered with the runtime system, but the object to which it refers was either reachable as of the most recent GC or allocated since the most recent GC.
# itab
* uvarint: Itab address
* bool: whether the data field of an Iface with this itab is a pointer
# osthread (M)
* uvarint: address of this os thread descriptor
* uvarint: Go internal id of thread
* uvarint: os's id for thread
# memstats
Dumps the first 26 fields of [MemStats](http://golang.org/pkg/runtime/#MemStats). All fields are dumped with a uvarint except the 25th which is dumped with 256 uvarints.
# queuedfinalizer
* uvarint: address of object that has a finalizer
* uvarint: pointer to FuncVal describing the finalizer
* uvarint: PC of finalizer entry point
* uvarint: type of finalizer argument
* uvarint: type of object
This finalizer is ready to run - the object to which it refers is unreachable. The runtime system just hasn't gotten around to running it yet.
# data
* uvarint: address of the start of the data segment
* string: contents of the data segment
* fieldlist: kind and offset of pointer-containing fields in the data segment.
# bss
Same format as data, but for the bss segment.
# defer
* uvarint: defer record address
* uvarint: containing goroutine
* uvarint: argp
* uvarint: pc
* uvarint: FuncVal of defer
* uvarint: PC of defer entry point
* uvarint: link to next defer record
# panic
* uvarint: panic record address
* uvarint: containing goroutine
* uvarint: type ptr of panic arg eface
* uvarint: data field of panic arg eface
* uvarint: ptr to defer record that's currently running
* uvarint: link to next panic record
# alloc/free profile record
* uvarint: record identifier
* uvarint: size of allocated object
* uvarint: number of stack frames. For each frame:
* - string: function name
* - string: file name
* - uvarint: line number
* uvarint: number of allocations
* uvarint: number of frees
# alloc sample record
* uvarint: address of object
* uvarint: alloc/free profile record identifier

178
heapdump14.md Normal file

@ -0,0 +1,178 @@
Heap dump format for other versions:
* [heapdump13](wiki/heapdump13)
# Introduction
Go 1.4 has a runtime/debug.WriteHeapDump function that writes all objects in the heap plus additional info (roots, goroutines, finalizers, etc.) to a file. The format of this file is specified here.
# Details
The file starts with the bytes of the string "go1.4 heap dump\n".
The rest of the file is a sequence of records. Records can be of several different kinds. Records will contain the following primitives:
* uvarint - a 64-bit unsigned integer encoded as in encoding/binary.{Put,Read}Uvarint
* string - a uvarint-encoded length followed by that many bytes of data
* bool - a uvarint-encoded 0 for false or 1 for true
* fieldlist - a description of the pointer-bearing portions of a memory region. It consists of repeated pairs of uvarints encoding a field kind and a field offset, followed by and end-of-list marker. The possible kinds are 1=Ptr, 2=Iface, and 3=Eface. 0=Eol is the end of list marker. The end of list marker does not have a corresponding offset.
Each record starts with a uvarint-encoded integer describing the type of the record:
* 0 = EOF
* 1 = object
* 2 = otherroot
* 3 = type
* 4 = goroutine
* 5 = stack frame
* 6 = dump params
* 7 = registered finalizer
* 8 = itab
* 9 = OS thread
* 10 = mem stats
* 11 = queued finalizer
* 12 = data segment
* 13 = bss segment
* 14 = defer record
* 15 = panic record
* 16 = alloc/free profile record
* 17 = alloc stack trace sample
The remaining fields of each record are type-dependent and are described below.
# EOF
An EOF record has no fields and must appear last.
# object
* uvarint: address of object
* string: contents of object
* fieldlist: describes pointer-containing fields of the object
The size of the contents string is the size of the containing sizeclass, not the size of the object itself. As such, contents size may be somewhat bigger than the contained object's type.
# otherroot
* string: textual description of where this root came from
* uvarint: root pointer
# type
* uvarint: address of type descriptor
* uvarint: size of an object of this type
* string: name of type
* bool: whether the data field of an interface containing a value of this type is a pointer
# goroutine (G)
* uvarint: address of descriptor
* uvarint: pointer to the top of stack (the currently running frame, a.k.a. depth 0)
* uvarint: go routine ID
* uvarint: the location of the go statement that created this goroutine
* uvarint: status
* bool: is a Go routine started by the system
* bool: is a background Go routine
* uvarint: approximate time the go routine last started waiting (nanoseconds since the Epoch)
* string: textual reason why it is waiting
* uvarint: context pointer of currently running frame
* uvarint: address of os thread descriptor (M)
* uvarint: top defer record
* uvarint: top panic record
Possible statuses:
* 0 = idle
* 1 = runnable
* 3 = syscall
* 4 = waiting
The wait fields must be present in all cases, but they only mean something if the status is "waiting".
# stack frame
* uvarint: stack pointer (lowest address in frame)
* uvarint: depth in stack (0 = top of stack)
* uvarint: stack pointer of child frame (or 0 if none)
* string: contents of stack frame
* uvarint: entry pc for function
* uvarint: current pc for function
* uvarint: continuation pc for function (where function may resume, if anywhere)
* string: function name
* fieldlist: list of kind and offset of pointer-containing fields in this frame
# dump params
* bool: big endian
* uvarint: pointer size in bytes
* uvarint: channel header size in bytes
* uvarint: starting address of heap
* uvarint: ending address of heap
* uvarint: thechar = architecture specifier
* string: GOEXPERIMENT environment variable value
* uvarint: runtime.ncpu
# finalizer
* uvarint: address of object that has a finalizer
* uvarint: pointer to FuncVal describing the finalizer
* uvarint: PC of finalizer entry point
* uvarint: type of finalizer argument
* uvarint: type of object
This finalizer has been registered with the runtime system, but the object to which it refers was either reachable as of the most recent GC or allocated since the most recent GC.
# itab
* uvarint: Itab address
* uvarint: address of type descriptor for contained type
# osthread (M)
* uvarint: address of this os thread descriptor
* uvarint: Go internal id of thread
* uvarint: os's id for thread
# memstats
Dumps the first 26 fields of [MemStats](http://golang.org/pkg/runtime/#MemStats). All fields are dumped with a uvarint except the 25th which is dumped with 256 uvarints.
# queuedfinalizer
* uvarint: address of object that has a finalizer
* uvarint: pointer to FuncVal describing the finalizer
* uvarint: PC of finalizer entry point
* uvarint: type of finalizer argument
* uvarint: type of object
This finalizer is ready to run - the object to which it refers is unreachable. The runtime system just hasn't gotten around to running it yet.
# data
* uvarint: address of the start of the data segment
* string: contents of the data segment
* fieldlist: kind and offset of pointer-containing fields in the data segment.
# bss
Same format as data, but for the bss segment.
# defer
* uvarint: defer record address
* uvarint: containing goroutine
* uvarint: argp
* uvarint: pc
* uvarint: FuncVal of defer
* uvarint: PC of defer entry point
* uvarint: link to next defer record
# panic
* uvarint: panic record address
* uvarint: containing goroutine
* uvarint: type ptr of panic arg eface
* uvarint: data field of panic arg eface
* uvarint: ptr to defer record that's currently running
* uvarint: link to next panic record
# alloc/free profile record
* uvarint: record identifier
* uvarint: size of allocated object
* uvarint: number of stack frames. For each frame:
* - string: function name
* - string: file name
* - uvarint: line number
* uvarint: number of allocations
* uvarint: number of frees
# alloc sample record
* uvarint: address of object
* uvarint: alloc/free profile record identifier

82
whygo.md Normal file

@ -0,0 +1,82 @@
# Introduction
Here's why: a list of people/organizations tell why they use Go.
This is partly redundant with https://code.google.com/p/go-wiki/wiki/GoUsers
# Why Go
* [Half a decade with Go](http://blog.golang.org/5years) by golang.org Blog
* [Why Learn Go](https://www.youtube.com/watch?v=FTl0tl9BGdc) by Rob Pike (YouTube)
* [Go at Google](http://www.infoq.com/presentations/Go-Google) by Rob Pike (YouTube)
* [Go at Google](http://talks.golang.org/2012/splash.article) by Rob Pike (Article)
* [5 things I love](https://www.youtube.com/watch?v=fsTOOPB1TBY) by Andrew Gerrand (dotGo 2014)
* [dl.google.com now served by Go](https://groups.google.com/d/msg/golang-nuts/BNUNbKSypE0/E4qSfpx9qI8J) by Brad Fitzpatrick
* [Is Google using Go internally?](https://golang.org/doc/faq#Is_Google_using_go_internally) by golang.org
* [The State of the Gopher](https://www.youtube.com/watch?v=4KFTacxqkcQ) by Brad Fitzpatrick (dotGo 2014)
* [Software I'm excited about](https://www.youtube.com/watch?v=sYukPc0y_Ro) by Brad Fitzpatrick (dotScale 2013)
* [I came for the easy concurrency I stayed for the easy composition](https://www.youtube.com/watch?v=4KFTacxqkcQ) by John Graham-Cumming (dotGo 2014)
* [Go 1.4+ Garbage Collection (GC) Plan and Roadmap](https://docs.google.com/document/d/16Y4IsnNRCN43Mx0NZc5YXZLovrHvvLhK_h0KN8woTO4/edit) by Richard L. Hudson
* [Five things that make Go fast](http://dave.cheney.net/2014/06/07/five-things-that-make-go-fast) by Dave Cheney
* [Another go at the Next Big Language](http://dave.cheney.net/2012/09/03/another-go-at-the-next-big-language) by Dave Cheney
* [Rewriting a large production system in Go](http://matt-welsh.blogspot.com/2013/08/rewriting-large-production-system-in-go.html) by Matt Welsh
* [Go is Boring](http://stevebate.silvrback.com/go-is-boring) by Steve Bate
* [Gopher Academy Blog](http://blog.gopheracademy.com/)
* [Kubernetes + Go = Crazy Delicious](http://blog.gopheracademy.com/birthday-bash-2014/kubernetes-go-crazy-delicious/) by Joe Beda
* [Why InfluxDB is written in Go](http://blog.gopheracademy.com/birthday-bash-2014/why-influxdb-uses-go/) by Paul Dix
* [How Continuum ended up being written in Go](http://blog.gopheracademy.com/birthday-bash-2014/apcera/) by Derek Collison
* [Building Street Address Autocomplete with Go](http://blog.gopheracademy.com/birthday-bash-2014/building-street-address-autocomplete/) by Matt Holt
* [Interview with Gophers](http://www.gophercon.in/blog/) by GopherCon India
* [Go at Docker](http://www.slideshare.net/jpetazzo/docker-and-go-why-did-we-decide-to-write-docker-in-go)
* [Go at YouTube (Vitess)](https://www.youtube.com/watch?v=qATTTSg6zXk) by Sugu Sougoumarane (FOSDEM 2014)
* [Go at YouTube (Vitess)](https://www.youtube.com/watch?v=midJ6b1LkA0&sns=gp) by Sugu Sougoumarane (I/O Bytes 2014)
* [Go at YouTube (Vitess)](https://www.youtube.com/watch?v=5yDO-tmIoXY) by Sugu Sougoumarane (dotScale 2014 2014)
* [Go at Facebook](https://github.com/facebookgo)
* [Go at Canonical (Juju)](https://groups.google.com/d/msg/golang-nuts/jLnMsUbYwrQ/isfMUvBOkEIJ) by Dave Cheney
* [Go at CloudFlare](http://blog.cloudflare.com/go-at-cloudflare/) by John Graham-Cumming
* [Go at Heroku](http://www.theregister.co.uk/2011/05/05/google_go/)
* [Go at Iron.io](http://blog.iron.io/2013/03/how-we-went-from-30-servers-to-2-go.html)
* [Go at BBC](http://www.quora.com/Is-Google-Go-ready-for-production-use/answer/Kunal-Anand)
* [Go at Dropbox](https://tech.dropbox.com/2014/07/open-sourcing-our-go-libraries/)
* [Go at Apcera](https://www.hakkalabs.co/articles/why-we-use-go) by Derek Collison
* [Go at fullstory](http://blog.gopheracademy.com/birthday-bash-2014/go-at-fullstory/) by Ian Rose
* [Go at Space Monkey](https://www.spacemonkey.com/blog/posts/go-space-monkey)
* [Go at Splice](https://blog.splice.com/golang-improved-simplicity-reduced-maintenance/) by Matt Aimonetti
* [Go at Runscope](http://blog.runscope.com/posts/go-at-runscope) by Frank Stratto
* [Go at SendGrid](https://sendgrid.com/blog/convince-company-go-golang/) by Tim Jenkins
* [Go at Disqus](http://blog.disqus.com/post/51155103801/trying-out-this-go-thing) by Matt Robenolt #1
* [Go at Disqus](http://highscalability.com/blog/2014/5/7/update-on-disqus-its-still-about-realtime-but-go-demolishes.html) by Matt Robenolt #2
* [Go at New York Times](http://open.blogs.nytimes.com//2014/07/10/emr-streaming-in-go/?_r=0) by JP Robinson
* [Go at SoundCloud](https://developers.soundcloud.com/blog/go-at-soundcloud) by Peter Bourgon
* [Go at PopTip](http://thenewstack.io/from-node-js-to-go-why-one-startup-made-the-switch/) by Alex Williams
* [Go at Toggl](http://blog.toggl.com/2012/09/moving-to-go/) by Alari Aho
* [Go at Torbit](http://torbit.com/blog/2013/02/19/big-data-at-torbit/) by Tylor Arndt
* [Go at Shopify](https://twitter.com/tobi/status/245873677483274240) by Tobias Lütke
* [Go at Bitly](http://word.bitly.com/post/29550171827/go-go-gadget)
* [Go at StatHat](http://blog.golang.org/building-stathat-with-go) by Patrick Crosby
* [Go at Moovweb](https://groups.google.com/forum/#!topic/golang-nuts/MeiTNnGhLg8/discussion) by Hampton Catlin
* [Go at Novartis](https://plus.google.com/114945221884326152379/posts/d1SVaqkRyTL) by Don Dwoske
* [Why I went from Python to Go (and not node.js)](http://jordanorelli.com/post/31533769172/why-i-went-from-python-to-go-and-not-node-js) by Jordan Orelli
* [Farewell Node.js](https://medium.com/code-adventures/farewell-node-js-4ba9e7f3e52b) by TJ Holowaychuk
* [Can Go really be that much faster than Python?](http://stackoverflow.com/questions/12574909/can-go-really-be-that-much-faster-than-python) on StackOverflow
* [Python to Go](http://www.slideshare.net/wuvist1/python-to-go) by Weng Wei
* [Why I Program in Go](http://tech.t9i.in/2013/01/why-program-in-go/) by Tahir Hashmi
* [DNS Server in Go](http://news.ntppool.org/2012/10/new-dns-server.html) by Ask Bjørn Hansen
# Benchmarks
* [Express vs Flask vs Go vs Sparkjava](https://medium.com/@tschundeee/express-vs-flask-vs-go-acc0879c2122) by Bijan
* [Comparing the Performance of Various Web Frameworks](http://www.infoq.com/news/2014/05/benchmark-web-framework) by Abel Avram
* [TechEmpower Web Framework Benchmarks](http://www.techempower.com/benchmarks/)
# Conference & Meetup
* [dotGo](http://www.dotgo.eu/)
* [Gophercon](http://www.gophercon.com/)
* [Gophercon India](http://www.gophercon.in/)
* [GothamGo](http://gothamgo.com/)