├── .gitignore ├── docs ├── .nojekyll ├── _Footer.md ├── Style.md ├── .gitignore ├── Diagnostics.md ├── RaceDetector.md ├── heapdump15.md ├── HttpFetch.md ├── images │ └── release-cycle.png ├── GoVsGenerics.md ├── Solaris.md ├── _Sidebar.md ├── GoGetProxyConfig.md ├── LearnTesting.md ├── GoGetTools.md ├── OlderVersions.md ├── HttpStaticFiles.md ├── SignalHandling.md ├── DragonFly-BSD.md ├── Windows.md ├── Questions.md ├── SimultaneousAssignment.md ├── Timeouts.md ├── FreeBSD.md ├── BoundingResourceUse.md ├── Linux.md ├── InstallFromSource.md ├── NoMeToo.md ├── LearnErrorHandling.md ├── Rationales.md ├── NetBSD.md ├── Ubuntu.md ├── Comments.md ├── GoStrings.md ├── Gopher.md ├── RateLimiting.md ├── Hashing.md ├── IssueLabels.md ├── LockOSThread.md ├── index.html ├── HostedContinuousIntegration.md ├── MultipleGoRoots.md ├── Iota.md ├── SendingMail.md ├── GithubAccess.md ├── Darwin.md ├── GoGenerateTools.md ├── GOPATH.md ├── Blogs.md ├── GerritAccess.md ├── Well-known-struct-tags.md ├── Range.md ├── NativeClient.md ├── InvalidFlag.md ├── SubRepositories.md ├── Training.md ├── README.md ├── Podcasts.md ├── InterfaceSlice.md ├── MutexOrChannel.md ├── NonEnglish.md ├── CommitMessage.md ├── PriorDiscussion.md ├── ProviderIntegration.md ├── TableDrivenTests.md ├── ChromeOS.md ├── Errors.md ├── SettingGOPATH.md ├── DashboardBuilders.md ├── SQLDrivers.md ├── CommonMistakes.md ├── OpenBSD.md ├── WindowsCrossCompiling.md ├── CodeTools.md ├── How-to-ask-for-help.md ├── CompilerOptimizations.md ├── WindowsBuild.md ├── Go1point1Gotchas.md ├── MinimumRequirements.md ├── InstallTroubleShooting.md ├── GerritBot.md ├── PanicAndRecover.md ├── LearnConcurrency.md ├── FileTreeDocumentation.md ├── CodeReview.md ├── SQLInterface.md ├── NewSpeakers.md ├── HandlingIssues.md ├── DevExp.md ├── SliceTricks.md ├── Gardening.md ├── PortingPolicy.md ├── WindowsDLLs.md ├── Gomote.md ├── CustomPprofProfiles.md ├── DesignDocuments.md ├── PerfDashboard.md ├── SuccessStories.md ├── Learn.md ├── GitHubCodeLayout.md ├── Benchmarks.md ├── vgo.md └── Switch.md └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ -------------------------------------------------------------------------------- /docs/.nojekyll: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/_Footer.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/Style.md: -------------------------------------------------------------------------------- 1 | See [CodeReviewComments](CodeReviewComments). -------------------------------------------------------------------------------- /docs/.gitignore: -------------------------------------------------------------------------------- 1 | www.md 2 | *.sublime-project 3 | 4 | *.sublime-workspace 5 | -------------------------------------------------------------------------------- /docs/Diagnostics.md: -------------------------------------------------------------------------------- 1 | Moved to [golang.org](https://tip.golang.org/doc/diagnostics.html). -------------------------------------------------------------------------------- /docs/RaceDetector.md: -------------------------------------------------------------------------------- 1 | Moved to http://golang.org/doc/articles/race_detector.html 2 | 3 | -------------------------------------------------------------------------------- /docs/heapdump15.md: -------------------------------------------------------------------------------- 1 | Page moved to https://github.com/golang/go/wiki/heapdump15-through-heapdump17 -------------------------------------------------------------------------------- /docs/HttpFetch.md: -------------------------------------------------------------------------------- 1 | # Fetching URLs with HTTP 2 | 3 | See the [example in net/http](http://golang.org/pkg/net/http/#example_Get). -------------------------------------------------------------------------------- /docs/images/release-cycle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KennethanCeyer/learn-golang-kr/HEAD/docs/images/release-cycle.png -------------------------------------------------------------------------------- /docs/GoVsGenerics.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | **This page has moved to a community-written document:** 4 | 5 | * [Summary of Go Generics Discussions](https://docs.google.com/document/d/1vrAy9gMpMoS3uaVphB32uVXX4pi-HnNjkMEgyAHX4N4/edit?pli=1#) 6 | -------------------------------------------------------------------------------- /docs/Solaris.md: -------------------------------------------------------------------------------- 1 | # Go on Solaris 2 | 3 | | **Kernel version** | **Architectures** | **Initial support version** | **Final support version** | 4 | |:-------------------|:------------------|:----------------------------|:--------------------------| 5 | | SunOS 5.11 | amd64 | Go 1.3 _*_ | | 6 | 7 | _*_ Go 1.5 or above is recommended. -------------------------------------------------------------------------------- /docs/_Sidebar.md: -------------------------------------------------------------------------------- 1 | # 목차 2 | 3 | + [Go를 시작하며](./#go를-시작하며) 4 | + [Go로 작업하기](./#go로-작업하기) 5 | + [Go에 대해 더 알아보기](./#go에-대해-더-알아보기) 6 | + [Go 커뮤니티](./#go-커뮤니티) 7 | + [Go 툴체인](./#go-툴체인) 8 | + [Go의 또 다른 위키들](./#go의-또-다른-위키들) 9 | + [Go로 동작하는 서비스들](./#go로-동작하는-서비스들) 10 | + [Go를 이용한 프로덕션에서의 문제해결](./#go를-이용한-프로덕션에서의-문제해결) 11 | + [Go 프로젝트에 기여](./#go-프로젝트에-기여) 12 | + [플랫폼 관련 정보](./#플랫폼-관련-정보) 13 | + [릴리즈 관련 정보](./#릴리즈-관련-정보) -------------------------------------------------------------------------------- /docs/GoGetProxyConfig.md: -------------------------------------------------------------------------------- 1 | Setting proxies for source code used by ` go get ` (listed in GoGetTools) 2 | 3 | ## git 4 | ``` 5 | $ git config [--global] http.proxy http://proxy.example.com:port 6 | ``` 7 | 8 | ## mercurial 9 | Edit ` ~/.hgrc ` and add the following: 10 | ``` 11 | [http_proxy] 12 | host=proxy.example.com:port 13 | ``` 14 | 15 | ## svn 16 | Edit ` ~/.subversion/servers ` and add the following: 17 | ``` 18 | [Global] 19 | http-proxy-host=proxy.example.com 20 | http-proxy-port=xxxx 21 | ``` -------------------------------------------------------------------------------- /docs/LearnTesting.md: -------------------------------------------------------------------------------- 1 | This page links to resources about testing in Go. 2 | 3 | - Read [How to Write Go Code](http://golang.org/doc/code.html), especially [Testing](https://golang.org/doc/code.html#Testing) 4 | - Study [Package testing](http://golang.org/pkg/testing) 5 | - Read [Why does Go not have assertions?](http://golang.org/doc/faq#assertions) 6 | - Read [Where is my favorite helper function for testing?](http://golang.org/doc/faq#testing_framework) 7 | - Watch [Testing Techniques](https://talks.golang.org/2014/testing.slide#1) 8 | - Read [TableDrivenTests](TableDrivenTests) 9 | - Read [Using Subtests and Sub-benchmarks](https://blog.golang.org/subtests) -------------------------------------------------------------------------------- /docs/GoGetTools.md: -------------------------------------------------------------------------------- 1 | # Installing Version Control Tools for ` go get ` 2 | 3 | The ` go get ` fetching of source code is done by using one of the following tools expected to be found on your system: 4 | 5 | * **svn** - Subversion, download at: http://subversion.apache.org/packages.html 6 | * **hg** - Mercurial, download at https://www.mercurial-scm.org/downloads 7 | * **git** - Git, download at http://git-scm.com/downloads 8 | * **bzr** - Bazaar, download at http://wiki.bazaar.canonical.com/Download 9 | 10 | For example, **git** is used for Github, **hg** is used for Bitbucket, etc. 11 | 12 | Refer [GoGetProxyConfig](GoGetProxyConfig) for setting proxies for these tools. -------------------------------------------------------------------------------- /docs/OlderVersions.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | This wiki page collects patches to build older version of Go on newer systems for 4 | testing and benchmark purposes. Please note that older Go versions are not 5 | supported, so don't use older version in production. 6 | 7 | # Go 1.0.x 8 | ## Go 1.0 9 | ``` 10 | diff -ur go/src/cmd/cc/funct.c go1/src/cmd/cc/funct.c 11 | --- go/src/cmd/cc/funct.c 2012-03-28 00:49:24.000000000 -0400 12 | +++ go1/src/cmd/cc/funct.c 2014-05-04 00:56:00.971460175 -0400 13 | @@ -269,7 +269,7 @@ 14 | goto bad; 15 | 16 | f = alloc(sizeof(*f)); 17 | - for(o=0; osym); o++) 18 | + for(o=0; osym); o++) 19 | f->sym[o] = S; 20 | 21 | t->funct = f; 22 | ``` -------------------------------------------------------------------------------- /docs/HttpStaticFiles.md: -------------------------------------------------------------------------------- 1 | # Serving Static Files with HTTP 2 | 3 | The HTTP package provides good support for efficiently serving static files. 4 | 5 | This is a complete Go webserver serving static files: 6 | 7 | ```go 8 | package main 9 | 10 | import "net/http" 11 | 12 | func main() { 13 | panic(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc")))) 14 | } 15 | ``` 16 | 17 | 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. 18 | 19 | See [net/http documentation](http://golang.org/pkg/net/http/) and in particular the [FileServer example](http://golang.org/pkg/net/http/#example_FileServer) for a more typical example. -------------------------------------------------------------------------------- /docs/SignalHandling.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | 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. 4 | 5 | # Example 6 | 7 | The following code demonstrates a program that waits for an interrupt signal and removes a temporary file when it occurs. 8 | 9 | ```go 10 | package main 11 | 12 | import ( 13 | "io/ioutil" 14 | "os" 15 | "os/signal" 16 | ) 17 | 18 | func main() { 19 | f, err := ioutil.TempFile("", "test") 20 | if err != nil { 21 | panic(err) 22 | } 23 | defer os.Remove(f.Name()) 24 | sig := make(chan os.Signal, 1) 25 | signal.Notify(sig, os.Interrupt) 26 | <-sig 27 | } 28 | ``` -------------------------------------------------------------------------------- /docs/DragonFly-BSD.md: -------------------------------------------------------------------------------- 1 | # Go on DragonFly BSD 2 | 3 | | **Kernel version** | **Architectures** | **Initial support version** | **Final support version** | 4 | |:------------------------|:------------------|:----------------------------|:--------------------------| 5 | | 4.6 or above | amd64 | Go 1.8 | | 6 | | 4.4.4 (EOL) | amd64 | Go 1.8 | | 7 | | 4.4 through 4.4.3 (EOL) | amd64 | Go 1.3 _*_ | Go 1.7.6 | 8 | | 3.8 through 4.2 (EOL) | amd64 | Go 1.3 _*_ | Go 1.7.6 | 9 | | 3.6 (EOL) | amd64, 386 | Go 1.3 | Go 1.4.3 | 10 | 11 | _*_ Go 1.5 or above is recommended. -------------------------------------------------------------------------------- /docs/Windows.md: -------------------------------------------------------------------------------- 1 | # Go under Microsoft Windows 2 | 3 | The Windows port is stable and officially supported. 4 | 5 | * See the [open Windows issues](https://github.com/golang/go/issues?q=is%3Aopen+is%3Aissue+label%3Aos-windows) on the issue tracker. 6 | 7 | | **Distributions** | **Architectures** | **Initial support version** | **Final support version** | 8 | |:-----------------------------------|:------------------|:----------------------------|:--------------------------| 9 | | Windows 7 or above | amd64, 386 | Go 1 _*_ | | 10 | | Windows Vista, Windows Server 2008 | amd64, 386 | Go 1 _*_ | Go 1.10.1 | 11 | | Windows XP, Windows Server 2003 | amd64, 386 | Go 1 _*_ | Go 1.10.1 | 12 | 13 | _*_ Go 1.5 or above is recommended. -------------------------------------------------------------------------------- /docs/Questions.md: -------------------------------------------------------------------------------- 1 | # Asking Questions 2 | 3 | Unlike many projects on GitHub, the Go project does not use its bug tracker for general discussion or asking questions. We only use our bug tracker for tracking bugs and tracking proposals going through the [Proposal Process](https://golang.org/s/proposal-process). 4 | 5 | For asking questions, see: 6 | 7 | * [The golang-nuts mailing list](https://groups.google.com/d/forum/golang-nuts) 8 | 9 | * [The Go Forum](https://forum.golangbridge.org/), a web-based forum 10 | 11 | * [Gophers Slack](https://gophers.slack.com), use the [invite app](https://invite.slack.golangbridge.org/) for access 12 | 13 | * [Stack Overflow](http://stackoverflow.com/questions/tagged/go) with questions tagged "go" 14 | 15 | * **IRC** channel #go-nuts on Freenode 16 | 17 | If we closed your question on GitHub, we apologize. Please ask the question on one of the above forums. -------------------------------------------------------------------------------- /docs/SimultaneousAssignment.md: -------------------------------------------------------------------------------- 1 | # Simultaneous Assignment 2 | 3 | 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. 4 | 5 | Simultaneous assignment in an if statement can improve readability, especially in test functions: 6 | ``` 7 | if got, want := someFunction(...), currTest.Expected; got != want { 8 | t.Errorf("%d. someFunction(...) = %v, want %v", currIdx, got, want) 9 | } 10 | ``` 11 | 12 | Swapping two values is also made simple using simultaneous assignment: 13 | 14 | ``` 15 | i, j = j, i 16 | ``` 17 | 18 | http://golang.org/ref/spec#Assignments -------------------------------------------------------------------------------- /docs/Timeouts.md: -------------------------------------------------------------------------------- 1 | # Timeouts and Deadlines 2 | 3 | To abandon synchronous calls that run too long, use the select statement with time.After: 4 | ```go 5 | import "time" 6 | 7 | c := make(chan error, 1) 8 | go func() { c <- client.Call("Service.Method", args, &reply) } () 9 | select { 10 | case err := <-c: 11 | // use err and reply 12 | case <-time.After(timeoutNanoseconds): 13 | // call timed out 14 | } 15 | ``` 16 | 17 | 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. 18 | 19 | ## References 20 | 21 | time.After: http://golang.org/pkg/time/#After 22 | 23 | select: http://golang.org/doc/go_spec.html#Select_statements 24 | 25 | blog post: http://blog.golang.org/2010/09/go-concurrency-patterns-timing-out-and.html -------------------------------------------------------------------------------- /docs/FreeBSD.md: -------------------------------------------------------------------------------- 1 | # Go on FreeBSD 2 | 3 | | **Kernel version** | **Architectures** | **Initial support version** | **Final support version** | 4 | |:-------------------|:------------------|:----------------------------|:--------------------------| 5 | | 12-CURRENT | amd64, arm, 386 | _**_ | | 6 | | 11-STABLE | amd64, arm, 386 | Go 1.7 | | 7 | | 10-STABLE | amd64, arm, 386 | Go 1.3 _*_ | | 8 | | 9-STABLE (EOL) | amd64, 386 | Go 1 _*_ | Go 1.9.5 | 9 | | 8-STABLE (EOL) | amd64, 386 | Go 1 _*_ | Go 1.9.5 | 10 | | 7-STABLE (EOL) | amd64, 386 | Go 1 | Go 1.1.2 | 11 | 12 | _*_ Go 1.5 or above is recommended. 13 | _**_ See https://golang.org/issues/22447. -------------------------------------------------------------------------------- /docs/BoundingResourceUse.md: -------------------------------------------------------------------------------- 1 | # Bounding resource use 2 | 3 | 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): 4 | 5 | ```go 6 | const ( 7 | AvailableMemory = 10 << 20 // 10 MB 8 | AverageMemoryPerRequest = 10 << 10 // 10 KB 9 | MaxOutstanding = AvailableMemory / AverageMemoryPerRequest 10 | ) 11 | 12 | var sem = make(chan int, MaxOutstanding) 13 | 14 | func Serve(queue chan *Request) { 15 | for { 16 | sem <- 1 // Block until there's capacity to process a request. 17 | req := <-queue 18 | go handle(req) // Don't wait for handle to finish. 19 | } 20 | } 21 | 22 | func handle(r *Request) { 23 | process(r) // May take a long time & use a lot of memory or CPU 24 | <-sem // Done; enable next request to run. 25 | } 26 | ``` 27 | 28 | ## References 29 | 30 | Effective Go's discussion of channels: http://golang.org/doc/effective_go.html#channels -------------------------------------------------------------------------------- /docs/Linux.md: -------------------------------------------------------------------------------- 1 | # Go on Linux 2 | 3 | | **Kernel version** | **Architectures** | **Initial support version** | **Final support version** | 4 | |:-------------------|:----------------------|:----------------------------|:--------------------------| 5 | | TBD | mips, mipsle | Go 1.8 | | 6 | | TBD | s390x | Go 1.7 | | 7 | | 4.8 or above | mips64le | Go 1.6 | | 8 | | TBD | mips64 | Go 1.6 | | 9 | | TBD | arm64, ppc64, ppc64le | Go 1.5 | | 10 | | 3.1 or above | arm | Go 1.1 _*_ | | 11 | | 2.6.23 or above | amd64, 386 | Go 1 _*_ | | 12 | 13 | _*_ Go 1.5 or above is recommended. -------------------------------------------------------------------------------- /docs/InstallFromSource.md: -------------------------------------------------------------------------------- 1 | # 소개 2 | 3 | 이 페이지는 http://golang.org/doc/install/source를 기준으로 다양한 운영체제에 대한 추가 지침사항을 제공하고 있습니다. 4 | 5 | ## C 도구 설치 6 | 7 | OS X 에서, [Xcode](http://developer.apple.com/Xcode/) 커맨드라인 도구로 C 컴파일러가 번들로 제공됩니다. 8 | Go를 컴파일하기 위해 전체 Xcode를 설치할 필요가 없습니다. 9 | 이미 Xcode 4.3 이상을 설치했다면 다운로드 환경 설정 패널의 구성 요소 탭에서 10 | 커맨드 라인 도구를 설치할 수 있습니다. 11 | 최신 버전의 Xcode에서는 Xcode를 열지 않고도 12 | `xcode-select --install ` 명령으로 커맨드 라인 도구를 설치 할 수 있습니다. 13 | 컴파일러가 작동되는지 확인하려면, 새로 생성된 터미널 창에서 그냥 `gcc`를 실행하세요 14 | `"gcc: command not found"` 에러가 보이지 않는 이상 여러분의 go는 준비가 된 것입니다. 15 | 16 | 우분투(Ubuntu) 데비안(Debian) 에서는, `sudo apt-get install gcc libc6-dev`를 이용하세요. 17 | 62비트 환경에서 32비트 바이너리 빌드를 원하시면 `libc6-dev-i386` 패키지가 필요합니다. 18 | 19 | 레드햇(RedHat) Centos 6에서는, `sudo yum install gcc glibc-devel`를 이용하세요. 20 | 62비트 환경에서 32비트 바이너리 빌드를 원하시면 21 | `glibc-devel.i386`와 `glibc-devel.x86_64` 패키지가 필요합니다. 22 | 23 | 윈도우즈(Windows) 에서는, [TDM-GCC](http://tdm-gcc.tdragon.net/)를 이용해 `gcc`를 설치해주세요. 24 | (설치한 프로그램의 `bin` 서브디렉토리를 `PATH` 변수로 잡았는지 확인해주세요.) 25 | Go는 현재 시그윈(Cygwin) 툴체인을 지원하지 않습니다. 26 | -------------------------------------------------------------------------------- /docs/NoMeToo.md: -------------------------------------------------------------------------------- 1 | When contributing to the Go issue tracker, please **do not** make comments like this: 2 | 3 | > +1 4 | 5 | or 6 | 7 | > :+1: 8 | 9 | or 10 | 11 | > Me too. 12 | 13 | or 14 | 15 | > I too would like to see this issue fixed. 16 | 17 | or 18 | 19 | > When is this issue going to be fixed? 20 | 21 | Such comments do not help fix issues. In fact, they make it harder by cluttering the discussion. The project admins will delete such comments as a matter of procedure (please don't be offended if we delete yours). 22 | 23 | Instead of commenting, you may [add a :+1: reaction](https://help.github.com/articles/about-discussions-in-issues-and-pull-requests/#reacting-to-ideas-in-issues-and-pull-requests) to the comment or issue. 24 | 25 | Of course, **please do comment** if your "me too" comment includes information that might help resolve the issue. This includes reports like this: 26 | 27 | > This issue also affects me on Windows 10 when running all.bat at revision c0ff33. 28 | 29 | (Although there's no need to make such a comment if an identical comment already exists.) 30 | 31 | Thanks! -------------------------------------------------------------------------------- /docs/LearnErrorHandling.md: -------------------------------------------------------------------------------- 1 | This page links to resources about error handling in Go. 2 | 3 | ## Getting Started 4 | 5 | - Read [Effective Go: Errors](https://golang.org/doc/effective_go.html#errors) 6 | - Code [A Tour of Go: Errors](http://tour.golang.org/methods/19) and do the [exercise](http://tour.golang.org/methods/20) 7 | - Study [The Go Programming Language Specification: Errors](http://golang.org/ref/spec#Errors) 8 | - Study [Package errors](http://golang.org/pkg/errors/) 9 | - Study [func fmt.Errorf](https://golang.org/pkg/fmt/#Errorf) 10 | 11 | ## Standard Practice 12 | 13 | - Read [Why does Go not have exceptions?](http://golang.org/doc/faq#exceptions) 14 | - Read [Error handling and Go](http://blog.golang.org/error-handling-and-go) 15 | - Read [Go by Example: Errors](https://gobyexample.com/errors) 16 | - Read [Errors are values](http://blog.golang.org/errors-are-values) 17 | - Read [golang/go/wiki: Errors](Errors) 18 | 19 | ## Advanced Topics 20 | 21 | - Read [Why is my nil error value not equal to nil?](http://golang.org/doc/faq#nil_error) 22 | - Read [Defer, Panic, and Recover](http://blog.golang.org/defer-panic-and-recover) -------------------------------------------------------------------------------- /docs/Rationales.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | This wiki entry will try to document the rationales behind some important language 4 | decisions besides what's included in the Go FAQ and Effective Go. 5 | 6 | # Language Features 7 | ### Why method receiver's base type cannot be pointer or interface? 8 | Reference: https://groups.google.com/forum/#!topic/golang-nuts/aqTwXHaSC_Y 9 | 10 | Go doesn't allow receiver's base type to be pointer to avoid possible ambiguity. 11 | Suppose you have: 12 | ``` 13 | type T blah 14 | type P *T 15 | 16 | func (t *T) String() string { ... } 17 | func (p P) String() string { ... } 18 | 19 | var p P 20 | ``` 21 | 22 | Then the meaning of the expression ` (*p).String() ` is ambiguous, because it can refer to 23 | both ` (*T).String ` and ` P.String `. 24 | 25 | Go doesn't allow receiver's base type to be interfaces, because interfaces already have methods. (TODO) 26 | 27 | ### Select with closed channel 28 | 29 | [Issue #11344](https://github.com/golang/go/issues/11344). 30 | 31 | ### Send to closed channel 32 | 33 | [Issue #18511](https://github.com/golang/go/issues/18511). 34 | 35 | # Memory Model 36 | 37 | # Standard Library -------------------------------------------------------------------------------- /docs/NetBSD.md: -------------------------------------------------------------------------------- 1 | # Go on NetBSD 2 | 3 | Go on NetBSD is not stable as of Go 1.8/Go 1.9. See https://tip.golang.org/doc/go1.9#known_issues and https://github.com/golang/go/issues/20852 4 | 5 | | **Kernel version** | **Architectures** | **Initial support version** | **Final support version** | 6 | |:----------------------|:------------------|:----------------------------|:--------------------------| 7 | | 8.0 or above | amd64, arm, 386 | | | 8 | | 7.0 through 7.1 | amd64, arm, 386 | Go 1.3 _*_ | | 9 | | 6.0 through 6.1 | amd64, arm, 386 | Go 1.3 _*_ | | 10 | | 5.0 through 5.2 (EOL) | amd64, 386 | Go 1 | Go 1.2.2 | 11 | 12 | _*_ Go 1.5 or above is recommended. 13 | 14 | # Preparing NetBSD for Go 15 | * install NetBSD 6.0 (remember to install pkgsrc in the last step) 16 | * install shells/bash and devel/git (do ` make package-install clean ` in ` /usr/pkgsrc/shells/bash ` and ` /usr/pkgsrc/devel/git `. 17 | * Using binary packages: ` pkgin install bash git ` -------------------------------------------------------------------------------- /docs/Ubuntu.md: -------------------------------------------------------------------------------- 1 | The Go project's official download page is at [https://golang.org/dl/](https://golang.org/dl/). 2 | 3 | There are some other options for Debian based systems like Ubuntu. These packages were not created by the Go project, and we don't support them, but they may be useful for you. 4 | 5 | Try: 6 | 7 | ``` 8 | $ sudo apt-get install golang-go 9 | ``` 10 | 11 | If that's too old for you, try: 12 | 13 | ``` 14 | $ sudo add-apt-repository ppa:gophers/archive 15 | $ sudo apt-get update 16 | $ sudo apt-get install golang-1.10-go 17 | ``` 18 | 19 | > **Note that golang-1.10-go puts binaries in /usr/lib/go-1.10/bin. If you want them on your PATH, you need to make that change yourself.** 20 | 21 | Using snaps also works quite well: 22 | 23 | ``` 24 | # This will give you the latest version of go 25 | $ snap install --classic go 26 | ``` 27 | > A restart is required for the command to be recognized. 28 | 29 | If you're using Ubuntu 16.04 LTS and are unable to install `golang-1.10-go`, then you can also use the `longsleep/golang-backports` PPA: 30 | 31 | ``` 32 | sudo add-apt-repository ppa:longsleep/golang-backports 33 | sudo apt-get update 34 | sudo apt-get install golang-go 35 | ``` -------------------------------------------------------------------------------- /docs/Comments.md: -------------------------------------------------------------------------------- 1 | # Comments 2 | 3 | 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. 4 | 5 | Subsequent sentences and/or paragraphs can give more details. Sentences should be properly punctuated. 6 | 7 | ```go 8 | // Package superman implements methods for saving the world. 9 | // 10 | // Experience has shown that a small number of procedures can prove 11 | // helpful when attempting to save the world. 12 | package superman 13 | ``` 14 | 15 | 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. 16 | 17 | ```go 18 | // enterOrbit causes Superman to fly into low Earth orbit, a position 19 | // that presents several possibilities for planet salvation. 20 | func enterOrbit() os.Error { 21 | ... 22 | } 23 | ``` -------------------------------------------------------------------------------- /docs/GoStrings.md: -------------------------------------------------------------------------------- 1 | Strings are **not** required to be UTF-8. Go source code **is** required 2 | to be UTF-8. There is a complex path between the two. 3 | 4 | In short, there are three kinds of strings. They are: 5 | 6 | 1. the substring of the source that lexes into a string literal. 7 | 1. a string literal. 8 | 1. a value of type string. 9 | 10 | Only the first is required to be UTF-8. The second is required to be 11 | written in UTF-8, but its contents are interpreted various ways 12 | and may encode arbitrary bytes. The third can contain any bytes at 13 | all. 14 | 15 | Try this on: 16 | 17 | ``` 18 | var s string = "\xFF語" 19 | ``` 20 | Source substring: ` "\xFF語" `, UTF-8 encoded. The data: 21 | 22 | ``` 23 | 22 24 | 5c 25 | 78 26 | 46 27 | 46 28 | e8 29 | aa 30 | 9e 31 | 22 32 | ``` 33 | 34 | String literal: ` \xFF語 ` (between the quotes). The data: 35 | 36 | ``` 37 | 5c 38 | 78 39 | 46 40 | 46 41 | e8 42 | aa 43 | 9e 44 | ``` 45 | 46 | The string value (unprintable; this is a UTF-8 stream). The data: 47 | 48 | ``` 49 | ff 50 | e8 51 | aa 52 | 9e 53 | ``` 54 | 55 | And for record, the characters (code points): 56 | ``` 57 | 58 | 語 U+8a9e 59 | ``` -------------------------------------------------------------------------------- /docs/Gopher.md: -------------------------------------------------------------------------------- 1 | The Go gopher was designed by [Renee French](https://reneefrench.blogspot.com/). 2 | The design is licensed under the Creative Commons 3.0 Attributions license. 3 | Read [this article](https://blog.golang.org/gopher) and watch [The Go Gopher A Character Study](https://www.youtube.com/watch?v=4rw_B4yY69k) for more details. 4 | 5 | ## Where can I find more gopher illustrations? 6 | 7 | * [gophers in the Go repository](https://github.com/golang/go/tree/master/doc/gopher) 8 | * [gopher vector](https://github.com/golang-samples/gopher-vector) 9 | * [gopher 3d](https://github.com/golang-samples/gopher-3d) 10 | * [golang graphics](https://github.com/mholt/golang-graphics) 11 | * [print-ready swimming gopher](https://gumroad.com/l/golang) 12 | * [go gopher vector](https://github.com/keygx/Go-gopher-Vector) 13 | * [gopher gala](http://www.gophergala.com/) 14 | * [gophericons](https://github.com/hackraft/gophericons) 15 | * [gophers by Egon Elbre](https://github.com/egonelbre/gophers) 16 | * [Go Gopher model (3d)](https://github.com/StickmanVentures/go-gopher-model) 17 | * [Gopher Artwork by Ashley McNamara](https://github.com/ashleymcnamara/gophers) 18 | * [Gopherize.me](https://gopherize.me/) - a Gopher avatar that's as unique as you 19 | -------------------------------------------------------------------------------- /docs/RateLimiting.md: -------------------------------------------------------------------------------- 1 | # Rate Limiting 2 | 3 | To limit the rate of operations per unit time, use a [time.Ticker](http://golang.org/pkg/time/#NewTicker). 4 | This works well for rates up to tens of operations per second. 5 | For higher rates, prefer a token bucket rate limiter such as [golang.org/x/time/rate.Limiter](https://godoc.org/golang.org/x/time/rate) (also search godoc.org for 6 | [rate limit](http://godoc.org/?q=rate+limit)). 7 | 8 | ```go 9 | import "time" 10 | 11 | rate := time.Second / 10 12 | throttle := time.Tick(rate) 13 | for req := range requests { 14 | <-throttle // rate limit our Service.Method RPCs 15 | go client.Call("Service.Method", req, ...) 16 | } 17 | ``` 18 | 19 | To allow some bursts, add a buffer to the throttle: 20 | ```go 21 | import "time" 22 | 23 | rate := time.Second / 10 24 | burstLimit := 100 25 | tick := time.NewTicker(rate) 26 | defer tick.Stop() 27 | throttle := make(chan time.Time, burstLimit) 28 | go func() { 29 | for t := range tick.C { 30 | select { 31 | case throttle <- t: 32 | default: 33 | } 34 | } // does not exit after tick.Stop() 35 | }() 36 | for req := range requests { 37 | <-throttle // rate limit our Service.Method RPCs 38 | go client.Call("Service.Method", req, ...) 39 | } 40 | ``` 41 | -------------------------------------------------------------------------------- /docs/Hashing.md: -------------------------------------------------------------------------------- 1 | Please consider move this into document for package ` hash `. 2 | 3 | # Hashing 4 | 5 | ## The hash.Hash interface 6 | 7 | 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. 8 | 9 | To input data, you use the Write method. For example: 10 | 11 | ```go 12 | h.Write(byteSlice) 13 | ``` 14 | 15 | or 16 | 17 | ```go 18 | io.Copy(h, file) 19 | ``` 20 | 21 | 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). 22 | 23 | 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 []byte parameter and return the new []byte. This can allow you to avoid allocating a new []byte each time you want the Sum. If you are summing often, you may do `md5sum := make([]byte, 16)` once and then do `h.Sum(md5sum[:0])` each time you want the new hash. 24 | 25 | If you want to reuse an already created hash, you can use `Reset()` to ensure it forgets all previously inputted data. -------------------------------------------------------------------------------- /docs/IssueLabels.md: -------------------------------------------------------------------------------- 1 | # Go Issue Tracker Labels 2 | 3 | The meanings of our the our [labels in the issue tracker](https://github.com/golang/go/labels). 4 | 5 | * **Builders** - something involving the Go continuous build/test system. 6 | * **DevExp** - issues involving Developer Experience Working Group's participation. 7 | * **Documentation** - issues involving documentation text only (no code). 8 | * **early-in-cycle** - Should be fixed early in the release cycle. 9 | * **Go2** - can't be done until a hypothetical Go 2 10 | * **GoCommand** - impacts the `cmd/go` tool 11 | * **HelpWanted** - we would like help on this issue. This label is used haphazardly. In general we want help on all issues. 12 | * **IDE** - This label is used to mark issues that affect code editors for Go. 13 | * **NeedsFix** - See https://github.com/golang/go/wiki/HandlingIssues 14 | * **NeedsDecision** - See https://github.com/golang/go/wiki/HandlingIssues 15 | * **NeedsInvestigation** - See https://github.com/golang/go/wiki/HandlingIssues 16 | * **Performance** - involving performance optimization (no functionality changes). 17 | * **Proposal-** - see https://github.com/golang/proposal 18 | * **ReleaseBlocker** - Has a release milestone, and must be fixed for that release. 19 | * **WaitingForInfo** - issue is not actionable because of missing required information, which needs to be provided. 20 | 21 | TODO: finish the rest -------------------------------------------------------------------------------- /docs/LockOSThread.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | Some libraries, especially graphical frameworks/libraries like Cocoa, OpenGL, libSDL all require it's 4 | called from the main OS thread or called from the same OS thread due to its use of thread local 5 | data structures. Go's runtime provides ` LockOSThread() ` function for this, but it's notoriously difficult 6 | to use correctly. 7 | 8 | # Solutions 9 | 10 | Russ Cox presented a good solution for this problem in this [thread](https://groups.google.com/d/msg/golang-nuts/IiWZ2hUuLDA/SNKYYZBelsYJ). 11 | 12 | ```Go 13 | package sdl 14 | 15 | // Arrange that main.main runs on main thread. 16 | func init() { 17 | runtime.LockOSThread() 18 | } 19 | 20 | // Main runs the main SDL service loop. 21 | // The binary's main.main must call sdl.Main() to run this loop. 22 | // Main does not return. If the binary needs to do other work, it 23 | // must do it in separate goroutines. 24 | func Main() { 25 | for f := range mainfunc { 26 | f() 27 | } 28 | } 29 | 30 | // queue of work to run in main thread. 31 | var mainfunc = make(chan func()) 32 | 33 | // do runs f on the main thread. 34 | func do(f func()) { 35 | done := make(chan bool, 1) 36 | mainfunc <- func() { 37 | f() 38 | done <- true 39 | } 40 | <-done 41 | } 42 | ``` 43 | 44 | And then other functions you write in package sdl can be like 45 | 46 | ```Go 47 | func Beep() { 48 | do(func() { 49 | // whatever must run in main thread 50 | }) 51 | } 52 | ``` -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Document 6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /docs/HostedContinuousIntegration.md: -------------------------------------------------------------------------------- 1 | A number of hosted continuous integration platforms have support for Go 2 | 3 | | Provider | Documentation | Notes | 4 | |:---------|:--------------|:------| 5 | | [AppVeyor](http://www.appveyor.com/) | [docs](https://bitbucket.org/appveyor/test-go) | Windows | 6 | | [CircleCI](https://circleci.com/) | [docs](https://circleci.com/docs/language-go/)| [howto-1](http://stackengine.com/golang-with-circleci/) [howto-2](https://medium.com/@jgautheron/publish-your-golang-binaries-in-github-with-circleci-e0b64cb21bf8) | 7 | | [Codeship](http://codeship.io) | [docs](https://www.codeship.io/documentation/languages-and-frameworks/go/) | | 8 | | [drone.io](http://drone.io/) | [docs](http://docs.drone.io/golang.html) | [open-source version](https://github.com/drone/drone) | 9 | | [Jenkins](https://jenkins-ci.org/) | [docs](https://wiki.jenkins-ci.org/display/JENKINS/Go+Plugin) | | 10 | | [Magnum CI](https://magnum-ci.com/) | [docs](https://magnum-ci.com/docs/go) | | 11 | | [Travis CI](http://travis-ci.org) | [docs](http://docs.travis-ci.com/user/languages/go/) | [howto](http://loads.pickle.me.uk/2015/08/22/easy-peasy-github-releases-for-go-projects-using-travis/), [go-client-api](https://github.com/AbletonAG/go-travis) | 12 | | [VSTS](https://www.visualstudio.com/team-services/) | [docs](https://docs.microsoft.com/en-us/vsts/build-release/apps/go/go) | | 13 | | [Wercker](http://wercker.com/) | [docs](http://devcenter.wercker.com/quickstarts/building/golang.html) | | | 14 | -------------------------------------------------------------------------------- /docs/MultipleGoRoots.md: -------------------------------------------------------------------------------- 1 | # 개요 2 | 3 | Go 해킹 방법 및 여러 `$GOROOT` 워크스페이스를 가지는 방법에 대한 팁입니다... 4 | 5 | 때때로 여러분은 Go tree의 여러 사본을 확인인 할 필요가 생깁니다. 아마 여러분은 여러 핵심 라이브러리들을 한꺼번에 변경하고 독립적으로 테스트할 필요가 있을 것입니다. 6 | 7 | 여러분이 `$HOME/go1`, `$HOME/go2` 등의 tree를 확인했다고 가정 해 봅시다. (딱히 이름이 중요한건 아닙니다.) 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. 8 | 9 | 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. 10 | 11 | 예시: 12 | 13 | ``` 14 | #!/bin/sh 15 | # Set GOROOT to the innermost enclosing directory containing 16 | # an AUTHORS file. Set GOPATH to its child called "got". 17 | dir=$(pwd) 18 | while true; do 19 | if [ -f "$dir/AUTHORS" ]; then 20 | export "GOROOT=$dir" 21 | export "GOPATH=$GOROOT/got" 22 | echo "GOROOT=$GOROOT" >&2 23 | echo "GOPATH=$GOPATH" >&2 24 | break 25 | fi 26 | dir=$(dirname "$dir") 27 | if [ "$dir" = / ]; then 28 | echo "Can't locate GOROOT". >&2 29 | exit 1 30 | fi 31 | done 32 | exec "$GOROOT/bin/go" "$@" 33 | ``` -------------------------------------------------------------------------------- /docs/Iota.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | Go's ` iota ` identifier is used 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. 4 | 5 | The values of iota is reset to 0 whenever the reserved word ` const ` appears in the source (i.e. each const block) and increments by one after each [ConstSpec](https://golang.org/ref/spec#ConstSpec) e.g. each Line. This can be combined with the constant shorthand (leaving out everything after the constant name) to very concisely define related constants. 6 | 7 | Iota: http://golang.org/doc/go_spec.html#Iota 8 | 9 | Constant declarations: http://golang.org/doc/go_spec.html#Constant_declarations 10 | 11 | # Examples 12 | 13 | The official spec has two great examples: 14 | 15 | http://golang.org/doc/go_spec.html#Iota 16 | 17 | Here's one from Effective Go: 18 | 19 | ``` 20 | type ByteSize float64 21 | 22 | const ( 23 | _ = iota // ignore first value by assigning to blank identifier 24 | KB ByteSize = 1 << (10 * iota) 25 | MB 26 | GB 27 | TB 28 | PB 29 | EB 30 | ZB 31 | YB 32 | ) 33 | ``` 34 | 35 | Weekday enum example - How iota is calculated - From [Learn Go Programming Blog](https://blog.learngoprogramming.com): 36 | 37 | ![How iota works](https://cdn-images-1.medium.com/max/2000/1*sfAHT3zk-WjxSDRIDMpdaA.gif) 38 | 39 | # Articles 40 | 41 | * [Ultimate Visual Guide to Go Enums and Iota](https://blog.learngoprogramming.com/golang-const-type-enums-iota-bc4befd096d3) _2017-10-09_ -------------------------------------------------------------------------------- /docs/SendingMail.md: -------------------------------------------------------------------------------- 1 | # Sending Mail 2 | 3 | See also: 4 | * [net/smtp](http://golang.org/pkg/net/smtp/) 5 | * [Email packages](https://github.com/golang/go/wiki/Projects#email) 6 | 7 | Streaming the body: 8 | 9 | ```go 10 | package main 11 | 12 | import ( 13 | "bytes" 14 | "log" 15 | "net/smtp" 16 | ) 17 | 18 | func main() { 19 | // Connect to the remote SMTP server. 20 | c, err := smtp.Dial("mail.example.com:25") 21 | if err != nil { 22 | log.Fatal(err) 23 | } 24 | defer c.Close() 25 | // Set the sender and recipient. 26 | c.Mail("sender@example.org") 27 | c.Rcpt("recipient@example.net") 28 | // Send the email body. 29 | wc, err := c.Data() 30 | if err != nil { 31 | log.Fatal(err) 32 | } 33 | defer wc.Close() 34 | buf := bytes.NewBufferString("This is the email body.") 35 | if _, err = buf.WriteTo(wc); err != nil { 36 | log.Fatal(err) 37 | } 38 | } 39 | ``` 40 | 41 | Authenticated SMTP: 42 | 43 | ```go 44 | package main 45 | 46 | import ( 47 | "log" 48 | "net/smtp" 49 | ) 50 | 51 | func main() { 52 | // Set up authentication information. 53 | auth := smtp.PlainAuth( 54 | "", 55 | "user@example.com", 56 | "password", 57 | "mail.example.com", 58 | ) 59 | // Connect to the server, authenticate, set the sender and recipient, 60 | // and send the email all in one step. 61 | err := smtp.SendMail( 62 | "mail.example.com:25", 63 | auth, 64 | "sender@example.org", 65 | []string{"recipient@example.net"}, 66 | []byte("This is the email body."), 67 | ) 68 | if err != nil { 69 | log.Fatal(err) 70 | } 71 | } 72 | ``` -------------------------------------------------------------------------------- /docs/GithubAccess.md: -------------------------------------------------------------------------------- 1 | # Github Access 2 | 3 | There are two types of Github access described here, with different powers & responsibilities. Only ask for access if you're an active member of the community. New contributors should participate in the Github & Gerrit review process for some time before requesting access. See https://golang.org/wiki/Gardening. 4 | 5 | (For Gerrit access, see https://golang.org/wiki/GerritAccess) 6 | 7 | ## Assignees 8 | 9 | The "go-assignees" group is a read-only group granting no special access, other than it allows the users in the group to be assigned issues. 10 | 11 | In general, Go doesn't use the "Assigned to" field of bugs much. Instead, we just leave a comment saying we'll work on it. But if you want this access, reference https://github.com/orgs/golang/teams/go-assignees and your Github username in your email requesting access. 12 | 13 | ## Editors 14 | 15 | The poorly named "go-approvers" group is the set of people who can edit metadata on issues. 16 | 17 | To request this type of access, reference https://github.com/orgs/golang/teams/go-approvers and your Github username in your email requesting access. 18 | 19 | Please do not edit any field you're not confident about. Feel free to ask for second opinions. 20 | 21 | ## Requesting Access 22 | 23 | To get request either of the access types above, file a bug (https://github.com/golang/go/issues/new?title=access:+&body=See+https://golang.org/wiki/GithubAccess) and list and state which access you want (its name and group URL). 24 | 25 | ## Once you have access 26 | 27 | Go help garden! See https://golang.org/wiki/Gardening. -------------------------------------------------------------------------------- /docs/Darwin.md: -------------------------------------------------------------------------------- 1 | # Go on Darwin 2 | 3 | | **Kernel version** | **Distributions** | **Architectures** | **Initial support version** | **Final support version** | 4 | |:-------------------|:--------------------------------|:-----------------------|:---------------|:----------| 5 | | 17 | macOS High Sierra 10.13, iOS 11 | amd64, arm, arm64, 386 | Go 1.7.1 _***_ | | 6 | | 16 | macOS Sierra 10.12, iOS 10 | amd64, arm, arm64, 386 | Go 1.7.1 _**_ | | 7 | | 15 | OS X El Capitan 10.11 | amd64, 386 | Go 1 _*_ | | 8 | | 15 | iOS 9 | arm, arm64 | Go 1.5 | | 9 | | 14 | OS X Yosemite 10.10 | amd64, 386 | Go 1 _*_ | | 10 | | 14 | iOS 7, iOS 8 | arm, arm64 | Go 1.5 | | 11 | | 13 | OS X Mavericks 10.9 | amd64, 386 | Go 1 _*_ | Go 1.10.1 | 12 | | 12 | OS X Mountain Lion 10.8 | amd64, 386 | Go 1 _*_ | Go 1.10.1 | 13 | | 11 | OS X Lion 10.7 | amd64, 386 | Go 1 _*_ | Go 1.7.6 | 14 | | 10 | Mac OS X Snow Leopard 10.6 | amd64, 386 | Go 1 | Go 1.4.3 | 15 | 16 | _*_ Go 1.5 or above is recommended. 17 | _**_ See https://github.com/golang/go/issues/16570 and https://github.com/golang/go/issues/19772. 18 | _***_ See https://github.com/golang/go/issues/22037. -------------------------------------------------------------------------------- /docs/GoGenerateTools.md: -------------------------------------------------------------------------------- 1 | [`go generate`](https://blog.golang.org/generate) is only useful if you have tools to use it with! Here is an incomplete list of useful tools that generate code. 2 | 3 | * [goyacc](https://godoc.org/golang.org/x/tools/cmd/goyacc) – Yacc for Go. 4 | * [stringer](https://godoc.org/golang.org/x/tools/cmd/stringer) – Implements `fmt.Stringer` interface for enums. 5 | * [gostringer](https://godoc.org/github.com/sourcegraph/gostringer) – Implements `fmt.GoStringer` interface for enums. 6 | * [jsonenums](https://github.com/campoy/jsonenums) – Implements `json.Marshaler` and `json.Unmarshaler` interfaces for enums. 7 | * [gojson](https://github.com/ChimeraCoder/gojson) - Generates go struct definitions from example json documents. 8 | * [vfsgen](https://github.com/shurcooL/vfsgen) - Generates a vfsdata.go file that statically implements the given virtual filesystem. 9 | * [goreuse](https://github.com/dc0d/goreuse) - Generates Go code using a package as a generic template by replacing definitions. 10 | * [embedfiles](https://4d63.com/embedfiles) - Embeds files into Go code. 11 | * [ragel](https://www.colm.net/open-source/ragel/) - State machine compiler 12 | * [peachpy](https://github.com/Maratyszcza/PeachPy) - x86-64 assembler embedded in Python, generates Go assembly 13 | * [bundle](https://godoc.org/golang.org/x/tools/cmd/bundle) - Bundle creates a single-source-file version of a source package suitable for inclusion in a particular target package. 14 | * [msgp](https://github.com/tinylib/msgp) - A Go code generator for MessagePack 15 | * [protobuf](https://github.com/golang/protobuf) - protobuf 16 | * [thriftrw](https://github.com/thriftrw/thriftrw-go) - thrift 17 | * [gogen-avro](https://github.com/actgardner/gogen-avro) - avro 18 | * [swagger-gen-types](https://github.com/dnephin/swagger-gen-types) - go types from swagger specifications -------------------------------------------------------------------------------- /docs/GOPATH.md: -------------------------------------------------------------------------------- 1 | # 개요 2 | 3 | GOPATH 환경변수는 Go 프로젝트와 해당 바이너리의 소스를 가지는 $GOROOT의 의부 디렉토리를 지정하는데 사용됩니다. 4 | 5 | 더 다양한 정보를 위해 [go command](http://golang.org/cmd/go/#hdr-GOPATH_environment_variable) and [go/build package](http://golang.org/pkg/go/build/) 문서를 확인해보시기 바랍니다. 6 | 7 | $GOPATH 변수는 리스트가 될 수 있기에, 이 문서의 나머지 부분은 별도로 명시하지 않는 한 첫 번째 요소는 $GOPATH를 의미합니다. 8 | 9 | ## 통합 GOPATH 10 | 11 | OS X 또는 Linux (bash)에서 다음의 값을 PATH에 추가하면 모든 $GOPATH/bin이 추가됩니다. 12 | ``` 13 | ${GOPATH//://bin:}/bin 14 | ``` 15 | 16 | ## 디렉토리 구성 17 | 18 | `"X/Y/Z"` 형태의 import 경로를 가진 패키지 소스는 아래와 같은 디렉토리 구성을 갖습니다. 19 | ``` 20 | $GOPATH/src/X/Y/Z 21 | ``` 22 | 23 | `"X/Y/Z"` 형태의 import 경로를 가진 바이너리 패키지는 아래와 같은 디렉토리 구성을 갖습니다. 24 | ``` 25 | $GOPATH/pkg/$GOOS_$GOARCH/X/Y/Z.a 26 | ``` 27 | 28 | 소스가 `$GOPATH/src/A/B`에 위치한 바이너리 명령어는 아래와 같은 디렉토리 구성을 갖습니다. 29 | ``` 30 | $GOPATH/bin/B 31 | ``` 32 | 33 | ## 리포지토리 통합 및 "go gettable" 프로젝트 생성 34 | 패키지를 가져 올 때 Go 도구는 패키지의 임포트 경로를 확인하여 URL을 찾습니다. 예를들어 여러분이 아래와 같은 커맨드라인을 사용할 때 35 | ``` 36 | go get github.com/go-kit/kit 37 | ``` 38 | go 도구는 https://github.com/go-kit/kit/에 호스트된 프로젝트에서 소스를 가져옵니다. 이때 리포지토리를 아래 경로로 클론합니다. 39 | ``` 40 | $GOPATH/src/github.com/go-kit/kit 41 | ``` 42 | 43 | 결과적으로, (리포지토리 대상 프로젝트에서) 동일한 리포지토리에있는 패키지를 가져 오는 경우 여러분은 "전체" 임포트 경로를 사용해야합니다 - 이 예제에 "kit" 패키지를 불러오기를 원하는 경우 "kit" 보다는 "github.com/go-kit/kit"을 임포트 하는 것이 좋습니다. 44 | 45 | ## 팁과 트릭들 46 | 47 | ### 단일 GOPATH를 사용하세요 48 | 49 | GOPATH가 디렉토리 목록일 수 있더라도 일반적으로 시스템의 모든 Go 코드에 대해 단일 GOPATH를 사용하는 것으로 충분합니다. "go get"으로 검색된 모든 패키지는 고유한 URL(그리고 각 디스크의 고유한 경로)을 갖기 때문에 Go 도구를 사용하여 빌드 할 때 둘 이상의 GOPATH 설정이 필요한 경우는 거의 존재하지 않습니다. 50 | 51 | ## FAQ 52 | ### `$GOPATH/src/cmd/mycmd/*.go`가 빌드되지 않는 이유가 뭔가요? 53 | Go 커맨드가 패키지를 찾을 때 대부분 `$GOROOT`를 먼저 살펴봅니다. 이는 디렉터리를 포함하기에 만약 `$GOROOT`에서 `cmd/` 디렉터리를 찾았다면 (위의 경우와 같이) 어떤 GOPATH에서도 해당 디렉터리를 찾지 않습니다. 이는 여러분의`math/matrix` 패키지와 `cmd/mycmd` 명령을 정의 할 수 없게합니다. 54 | -------------------------------------------------------------------------------- /docs/Blogs.md: -------------------------------------------------------------------------------- 1 | A set of blogs dedicated to Go. 2 | 3 | NOTE: Please don't add individual blog entries to this page. Those belong in [articles](Articles) instead. 4 | 5 | ## English 6 | 7 | * [The official Go Blog](https://blog.golang.org) - For in depth posts by the Go team 8 | * [Gopher Academy Blog](http://blog.gopheracademy.com/) 9 | * [Dave Cheney's Blog](http://dave.cheney.net) 10 | * [Dave Cheney's Resources for Go Programmers](http://dave.cheney.net/resources-for-new-go-programmers) 11 | * [spf13's Go Blog](http://spf13.com/post/) 12 | * [Katrina Owen's Blog](http://whipperstacker.com/) 13 | * [Mat Ryer's Medium Blog](https://medium.com/@matryer) 14 | * [Matt Aimonetti's Blog](http://matt.aimonetti.net/) 15 | * [Marcio.io](http://marcio.io/) 16 | * [Carlos Becker's Blog](http://carlosbecker.com/) 17 | * [Ardan Studios Going Go](http://www.goinggo.net/) 18 | * [The Golang Weekly](http://golangweekly.com/) 19 | * [Alex Edward's Golang Posts](http://www.alexedwards.net/blog/category/golang) 20 | * [GoLang Tutorials](http://golangtutorials.blogspot.com/) 21 | * [Mathias Lafeldt's Blog](https://mlafeldt.github.io/) 22 | * [Marcelo Magallon's Blog](http://blog.ksub.org/bytes/) 23 | * [Mina Andrawos's Golang Posts](http://www.minaandrawos.com/category/golang-2/) 24 | * [Aliaksandr Pliutau's Golang Blog](http://pliutau.com/) 25 | * [Johan Brandhorst's Golang Blog](https://jbrandhorst.com) 26 | * [Christoph Berger's Applied Go Blog](https://appliedgo.net) 27 | * [Jon Calhoun's Blog](https://www.calhoun.io/) 28 | * [Inanc Gumus's Learn Go Programming Blog](https://blog.learngoprogramming.com) 29 | 30 | ## Portuguese 31 | 32 | * [Eduardo Nunes Pereira](https://medium.com/@eduardonunespereira) 33 | * [Gopher Brasil](http://gopher.net.br) 34 | 35 | ## Spanish 36 | * [Golang Argentina](https://golang.com.ar) 37 | 38 | ## Chinese 39 | * [虞双齐的博客-Golang](https://yushuangqi.com/tags/golang.html) -------------------------------------------------------------------------------- /docs/GerritAccess.md: -------------------------------------------------------------------------------- 1 | # Gerrit Access 2 | 3 | There are two types of Gerrit access described here, with different powers & responsibilities. Only ask for access if you're an active member of the community. New contributors should participate in the Gerrit code review process for some time before requesting access. 4 | 5 | (For Github access, see https://golang.org/wiki/GithubAccess) 6 | 7 | ## Approver Access ("approvers") 8 | 9 | Approver access gives you power to +2 CLs and submit them. 10 | 11 | Rules for voting +2 on changes: only +2 things that you're very confident in, and generally only in a directory (or package) that you normally "own", unless it's trivial and obviously correct. 12 | 13 | Rules for submitting changes: if a change touches an area that you own, you can submit any changes after a +2. But elsewhere only submit your own changes after receiving a +2 from the owner of that area. 14 | 15 | To request this access, reference https://go-review.googlesource.com/#/admin/groups/1005,members in your bug. See below. 16 | 17 | ## Trybot Access ("may-start-trybots") 18 | 19 | Trybot access lets you kick off a trybot run, testing a CL in Gerrit against the most common builders. The Trybots run in a somewhat-secure and somewhat-isolated environment, but they're not perfectly security hardened. You must skim the CL for anything malicious before starting Trybots. 20 | 21 | To request this access, reference https://go-review.googlesource.com/#/admin/groups/1030,members in your bug. See below. 22 | 23 | # Requesting Access 24 | 25 | To get request either of the access types above, file a bug (https://github.com/golang/go/issues/new?title=access:+&body=See+https://golang.org/wiki/GerritAccess) and list and state which access you want (its name and group URL), and state your Gerrit email address. 26 | 27 | ## Once you have access 28 | 29 | Go help garden! See https://golang.org/wiki/Gardening. -------------------------------------------------------------------------------- /docs/Well-known-struct-tags.md: -------------------------------------------------------------------------------- 1 | # Well-known struct tags 2 | ## Background 3 | 4 | Go offers [struct tags](https://golang.org/ref/spec#Tag) which are discoverable via reflection. These enjoy a wide range of use in the standard library in the JSON/XML and other encoding packages. 5 | 6 | The community welcomed them and has built ORMs, further encodings, flag parsers and much more around them since, especially for these tasks, single-sourcing is beneficial for data structures. 7 | 8 | ## Problem description 9 | Due to increased usage of Go and thus Go [struct tags](https://golang.org/ref/spec#Tag), clashes become inevitable. 10 | 11 | ## Solution 12 | The list below is a best effort to document well-known struct tags used by packages which are available to the public. 13 | 14 | ## Format of the list 15 | * Struct tag as extracted by calling https://godoc.org/reflect#StructTag.Get with this tag as the `key` argument. 16 | * Documentation link of this package using https://godoc.org 17 | 18 | ### Example entry 19 | Tag | Documentation 20 | ----|----- 21 | xml | https://godoc.org/encoding/xml 22 | 23 | ### Change Management 24 | List entries can be added by anyone who creates a public package where a new tag is used. 25 | List entries can be removed when the links to the package documentation stops working or the author(s) of that package requests it. 26 | 27 | ## List of well-known struct tags 28 | Tag | Documentation 29 | ----------|--------------- 30 | xml | https://godoc.org/encoding/xml 31 | json | https://godoc.org/encoding/json 32 | asn1 | https://godoc.org/encoding/asn1 33 | reform | https://godoc.org/gopkg.in/reform.v1 34 | bigquery | https://godoc.org/cloud.google.com/go/bigquery 35 | datastore | https://godoc.org/cloud.google.com/go/datastore 36 | spanner | https://godoc.org/cloud.google.com/go/spanner 37 | bson | https://godoc.org/labix.org/v2/mgo/bson 38 | gorm | https://godoc.org/github.com/jinzhu/gorm -------------------------------------------------------------------------------- /docs/Range.md: -------------------------------------------------------------------------------- 1 | # Range Clauses 2 | 3 | Spec: http://golang.org/doc/go_spec.html#For_statements 4 | 5 | ## Summary 6 | 7 | A range clause provides a way to iterate over an array, slice, string, map, or channel. 8 | 9 | ## Example 10 | 11 | ```go 12 | for k, v := range myMap { 13 | log.Printf("key=%v, value=%v", k, v) 14 | } 15 | 16 | for v := range myChannel { 17 | log.Printf("value=%v", v) 18 | } 19 | 20 | for i, v := range myArray { 21 | log.Printf("array value at [%d]=%v", i, v) 22 | } 23 | ``` 24 | 25 | ## Reference 26 | 27 | If only one value is used on the left of a range expression, it is the 1st value in this table. 28 | 29 | | Range expression | 1st value | 2nd value (optional) | notes | 30 | |:-----------------|:----------|:---------------------|:------| 31 | | array or slice a ` [n]E `, ` *[n]E `, or ` []E ` | index ` i int ` | ` a[i] ` E | 32 | | string s string type | index ` i int ` | rune ` int ` | range iterates over Unicode code points, not bytes | 33 | | map m ` map[K]V ` | key ` k K ` | value ` m[k] ` V | 34 | | channel c chan E | element ` e E ` | _none_ | 35 | 36 | ## Gotchas 37 | 38 | When iterating over a slice or map of values, one might try this: 39 | 40 | ```go 41 | items := make([]map[int]int, 10) 42 | for _, item := range items { 43 | item = make(map[int]int, 1) // Oops! item is only a copy of the slice element. 44 | item[1] = 2 // This 'item' will be lost on the next iteration. 45 | } 46 | ``` 47 | 48 | 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: 49 | 50 | ```go 51 | items := make([]map[int]int, 10) 52 | for i := range items { 53 | items[i] = make(map[int]int, 1) 54 | items[i][1] = 2 55 | } 56 | ``` -------------------------------------------------------------------------------- /docs/NativeClient.md: -------------------------------------------------------------------------------- 1 | Go 1.3 includes support for generating x86-32 and x86-64 binaries for Google Native Client (NaCl). 2 | 3 | NaCl is a collection of related technologies. 4 | 5 | 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. 6 | 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. 7 | 1. To abstract away the syscall-like interface, NaCl defines a stable runtime API called the integrated runtime (IRT). 8 | 1. Using the IRT, Google Chrome defines an API called Pepper (aka PPAPI) that NaCl-based plugins use to interact with the browser. 9 | 1. To abstract away the machine-specific binary formats, NaCl defines an LLVM-based architecture-independent format called PNaCl. 10 | 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. 11 | 12 | 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). 13 | 14 | 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. 15 | 16 | There are no concrete plans to support PNaCl (5 and 6 in the list). 17 | 18 | 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. -------------------------------------------------------------------------------- /docs/InvalidFlag.md: -------------------------------------------------------------------------------- 1 | # `invalid flag in #cgo CFLAGS` 2 | 3 | This page describes the background for build errors like `invalid flag in #cgo CFLAGS` and what you can do about them. 4 | 5 | [CVE-2018-6574](https://nvd.nist.gov/vuln/detail/CVE-2018-6574) described a potential security violation in the go tool: running `go get` downloads and builds Go code from the Internet, Go code that uses cgo can specify options to pass to the compiler, so careful use of `-fplugin` can cause `go get` to execute arbitrary code. While it is difficult to block every possible way that the compiler might be attacked, we have chosen to block the obvious ones. 6 | 7 | As described at [issue 23672](https://golang.org/issue/23672), this is done by using a whitelist of compiler/linker options that are permitted during `go get`, `go build`, and friends. When cgo code tries to use to pass an option that is not on the whitelist, the go tool will report an error `invalid flag in #cgo CFLAGS` (or `#cgo LDFLAGS`, `pkg-config --cflags`, `pkg-config --ldflags`, and so forth). 8 | 9 | This whitelist is new in releases 1.8.7, 1.9.4, and 1.10, and all subsequent releases. 10 | 11 | ## What can I do? 12 | 13 | If this happens to you, and the option is benign, you should do two things: 14 | 1. Set the environment variable `CGO_CFLAGS_ALLOW` (or `CGO_LDFLAGS_ALLOW`, `CGO_CXXFLAGS_ALLOW`, and so forth) to a [regexp](https://golang.org/pkg/regexp/) that matches the option. 15 | 2. [File a bug](https://golang.org/issue/new) requesting that the option be added to the whitelist. Be sure to include the complete error message and, if possible, a description of the code you are building. 16 | 17 | ## Why not use a blacklist? 18 | 19 | Because if some new unsafe option is added to a compiler, all existing Go releases will become immediately vulnerable. 20 | 21 | ## Why not get a complete list of compiler options and whitelist all of them? 22 | 23 | Because there are hundreds of options, and there is no clear way to get a complete list. Many compiler and linker options are target dependent, and thus only reported on specific platforms or in specific configurations. The documentation is known to be incomplete. -------------------------------------------------------------------------------- /docs/SubRepositories.md: -------------------------------------------------------------------------------- 1 | These packages are part of the Go Project but outside the main Go tree. 2 | 3 | They are developed under looser [compatibility requirements](http://golang.org/doc/go1compat.html) than the Go core. In general, they will support the previous two releases and tip. 4 | 5 | Install them with "go get". 6 | 7 | * [[docs](https://godoc.org/golang.org/x/tools)] [[source](https://go.googlesource.com/tools)] ` golang.org/x/tools ` — godoc, vet, cover, and other tools. 8 | * [[docs](https://godoc.org/golang.org/x/mobile)] [[source](https://go.googlesource.com/mobile)] ` golang.org/x/mobile ` — libraries and build tools for Go on Android. 9 | 10 | * [[docs](https://godoc.org/golang.org/x/crypto)] [[source](https://go.googlesource.com/crypto)] ` golang.org/x/crypto ` — additional cryptography packages. 11 | * [[docs](https://godoc.org/golang.org/x/image)] [[source](https://go.googlesource.com/image)] ` golang.org/x/image ` — additional imaging packages. 12 | * [[docs](https://godoc.org/golang.org/x/net)] [[source](https://go.googlesource.com/net)] ` golang.org/x/net ` — additional networking packages. 13 | * [[docs](https://godoc.org/golang.org/x/sys)] [[source](https://go.googlesource.com/sys)] ` golang.org/x/sys ` — for low-level interactions with the operating system. 14 | * [[docs](https://godoc.org/golang.org/x/text)] [[source](https://go.googlesource.com/text)] ` golang.org/x/text ` — packages for working with text. 15 | 16 | * [[docs](https://godoc.org/golang.org/x/blog)] [[source](https://go.googlesource.com/blog)] ` golang.org/x/blog ` — the content and server program for [blog.golang.org](http://blog.golang.org). 17 | 18 | 19 | * [[docs](https://godoc.org/golang.org/x/review)] [[source](https://go.googlesource.com/review)] ` golang.org/x/review ` — tools for code review. 20 | * [[docs](https://godoc.org/golang.org/x/benchmarks)] [[source](https://go.googlesource.com/benchmarks)] ` golang.org/x/benchmarks ` 21 | 22 | * [[docs](https://godoc.org/golang.org/x/exp)] [[source](https://go.googlesource.com/exp)] ` golang.org/x/exp ` — experimental code (handle with care). 23 | 24 | [List of all packages in sub-repositories](https://godoc.org/-/subrepo) -------------------------------------------------------------------------------- /docs/Training.md: -------------------------------------------------------------------------------- 1 | Commercial providers of Go training 2 | 3 | ## On-line 4 | 5 | * [Mastering Go Programming](https://www.packtpub.com/application-development/mastering-go-programming-video) - A comprehensive Go video training course 6 | * [Golang - From Beginner to Advanced - Romeo Mihalcea](https://www.devcasts.io/course/golang-from-beginner-to-advanced/) 7 | * [Golang Tutorials - Sathish VJ](http://golangtutorials.blogspot.com/2011/05/table-of-contents.html) - A free online class. 8 | * [Learn Go - Codementor.io](https://www.codementor.io/go) - Beginner level online class. 9 | * [Learning to Program in Go - Chris Hawkes](https://www.youtube.com/playlist?list=PLei96ZX_m9sVSEXWwZi8uwd2vqCpEm4m6) - Free video tutorial for beginner Go programming. 10 | * [O'Reilly Go Fundamentals](http://shop.oreilly.com/category/learning-path/go-fundamentals.do) - Video training series. 11 | * [Pluralsight.com](http://www.pluralsight.com/tag/golang) - Offers 5 classes at beginner and advanced levels. 12 | * [Master Go](https://appliedgo.com/p/mastergo/) - A paid online video course on Go for developers 13 | * [Learn to Create Web Applications using Go](https://www.usegolang.com/) - A paid online video course and book about Web programming with Go 14 | * [Golang tutorial](https://hackr.io/tutorials/learn-golang) - Learn Go from the best online golang tutorials submitted & voted by the golang programming community. 15 | 16 | ## Classroom and In-Person 17 | 18 | * [Ardan Labs](https://www.ardanlabs.com/) - Offering customized on-site live training classes. 19 | * [Boss Sauce Creative](https://bosssauce.it/services/training) - Personalized or track-based Go training for teams. 20 | * [Brian Ketelsen](https://www.brianketelsen.com/) - In-person, remote, and online training classes for individuals and companies. 21 | * [Gopher Guides](https://www.gopherguides.com/) - Customized In-person, remote, and online training classes. Training for Developers by Developers. Lead Instructors: [Mark Bates](http://www.gopherguides.com/team/mark.bates), [Cory LaNou](http://www.gopherguides.com/team/cory.lanou) 22 | * [Web Development in Go](http://goblimey.com/courses/go.for.oo.devs.html) - three days, 26th-28th June 2017, London. -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 |

:page_with_curl: learn-golang-kr

2 |

golang-kr

3 |

golang을 시작하며 필요한 모든 정보를 취합하는 리포지토리 입니다.

4 | 5 | ## 시작하며 6 | 7 | 이 리포지토리는 한국에 golang 가이드가 너무 없는 것에 우울하여 귀차니즘을 무릎쓰고 만들어졌습니다. 8 | 9 | 아시는분들은 아시겠지만 국내 golang 커뮤니티가 많이 활성화되어 있지 않습니다. 10 | 11 | 이런 작은 프로젝트를 시작으로 다른 Gopher분들도 기여와 커뮤니티에 많이 참여하셨으면 좋겠습니다. 12 | 13 | ## 목차 14 | 15 | + [Go를 시작하며](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#go를-시작하며) 16 | + [Go 작업하기](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#go로-작업하기) 17 | + [Go에 대해 더 알아보기](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#go에-대해-더-알아보기) 18 | + [Go 커뮤니티](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#go-커뮤니티) 19 | + [Go 툴체인](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#go-툴체인) 20 | + [Go의 또 다른 위키들](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#go의-또-다른-위키들) 21 | + [Go로 동작하는 서비스들](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#go로-동작하는-서비스들) 22 | + [Go를 이용한 프로덕션에서의 문제해결](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#go를-이용한-프로덕션에서의-문제해결) 23 | + [Go 프로젝트에 기여](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#go-프로젝트에-기여) 24 | + [플랫폼 관련 정보](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#플랫폼-관련-정보) 25 | + [릴리즈 관련 정보](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#릴리즈-관련-정보) 26 | 27 | ## 기여 28 | 29 | ### 규칙 30 | 31 | 1. 문서는 GitHub Wiki에서 관리합니다. 32 | 2. 참고한 문서는 그 출처를 명시하도록 합니다. 33 | 3. 기여는 GitHub의 Pull Request를 이용하여 진행합니다. 34 | 4. 문서는 되도록 간결체를 사용합니다. 35 | 5. 스크린샷이 필요한 경우 IDE는 `JetBrains GoLand` 스크린샷은 자유롭게 올리되 Pull Request에 기록합니다. 36 | 6. [GPG sign](https://help.github.com/articles/signing-commits-using-gpg/)이 된 커밋을 올려주시기 바랍니다. 37 | 38 | ## 로드맵 39 | 40 | - [ ] [golang/go Wiki](https://github.com/golang/go/wiki) 번역 41 | - [ ] [golang.org/doc/code.html](https://golang.org/doc/code.html) 번역 42 | - [ ] [golang.org/doc/effective_go.html](https://golang.org/doc/effective_go.html) 번역 43 | - [ ] Go 테스트 베스트프렉티스 44 | - [ ] 쉬운 설치가이드 작성 45 | - [ ] 네이밍 컨벤션 작성 46 | - [ ] 라이브러리 배포 및 관리 방법 작성 47 | - [ ] Go 엔터프라이즈 아키텍처 설계 방법 작성 48 | - [ ] Go를 사용한 제품들 49 | -------------------------------------------------------------------------------- /docs/Podcasts.md: -------------------------------------------------------------------------------- 1 | ## Podcast shows 2 | * [GolangShow](http://golangshow.com/) – Weekly podcast since June 2015, in Russian language. 3 | * [Go Time](http://gotime.fm) - Erik St. Martin, Carlisia Campos, Brian Ketelsen, recorded weekly and streamed live at 3PM EST at http://changelog.com/live 4 | * [Go Gab](https://www.briefs.fm/go-gab) - A podcast about everything Go. Episodes are short: about 3 minutes each. 5 | 6 | ## Podcast episodes 7 | A collection of podcast episodes that cover Go programming. Please keep items in reverse chronological order (most recent first) 8 | * [The Go Language - Hipsters #67](https://hipsters.tech/linguagem-go-hipsters-67/) (_in portuguese_) _2017-10-24_ 9 | * [The Go Programming Language 2 - Castálio Podcast #87](http://castalio.info/episodio-87-linguagem-de-programacao-go-parte-2.html) (_in portuguese_) _2017-02-13_ 10 | * [The Go Programming Language 1 - Castálio Podcast #86](http://castalio.info/episodio-86-linguagem-de-programacao-go-parte-1.html) (_in portuguese_) _2017-02-06_ 11 | * [Little chat about Go Lang](https://soundcloud.com/rdshipit/capycast-2-golang) (_in portuguese_) _2016-03-27_ 12 | * [Programming in Go with Michael Van Sickle](https://www.dotnetrocks.com/?show=1203) _2015-10-13_ 13 | * [Go on the Web](http://thewebplatform.libsyn.com/55-go-on-the-web) _2015-08-05_ 14 | * [Fatherhood with Andrew Gerrand](http://beatsryetypes.com/episodes/2015/05/18/episode-16-fatherhood-with-andrew-gerrand.html) _2015-05-15_ 15 | * [Talking with Go Developers at GopherCon India 2015](https://soundcloud.com/thenewstackanalysts/show-33-gophercon-india-2015) _2015-04-01_ 16 | * [Interview with CC4CS talking about Security in Go](https://go.unicorn.tv/podcasts/interview-with-cc4cs-talking-about-security-in-go) _2015-03-06_ 17 | * [Golang Best Practices](https://go.unicorn.tv/podcasts/golang-best-practices) _2014-09-08_ 18 | * [An Introduction to the Go Programming Language with Andrew Gerrand](http://hanselminutes.com/416/an-introduction-to-the-go-programming-language-with-andrew-gerrand) _2014-03-28_ 19 | * [FLOSS Weekly #284: The Go Language](https://twit.tv/shows/floss-weekly/episodes/284) _2014-02-19_ 20 | * [Series: The Go Language - GrokPodcast](http://www.grokpodcast.com/series/a-linguagem-go/) (_in portuguese_) _2013-07-17_ -------------------------------------------------------------------------------- /docs/InterfaceSlice.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | Given that you can assign a variable of any type to an ` interface{} `, often people will try code like the following. 4 | ``` 5 | var dataSlice []int = foo() 6 | var interfaceSlice []interface{} = dataSlice 7 | ``` 8 | This gets the error 9 | ``` 10 | cannot use dataSlice (type []int) as type []interface { } in assignment 11 | ``` 12 | 13 | The question then, "Why can't I assign any slice to an ` []interface{} `, when I can assign any type to an ` interface{} `?" 14 | 15 | ## Why? 16 | 17 | There are two main reasons for this. 18 | 19 | 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. 20 | 21 | Well, is it? A variable with type ` []interface{} ` has a specific memory layout, known at compile time. 22 | 23 | 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. 24 | 25 | 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. 26 | 27 | The result is that you cannot quickly assign something of type ` []MyType ` to something of type ` []interface{} `; the data behind them just look different. 28 | 29 | ## What can I do instead? 30 | 31 | It depends on what you wanted to do in the first place. 32 | 33 | 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. 34 | 35 | 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. 36 | ``` 37 | var dataSlice []int = foo() 38 | var interfaceSlice []interface{} = make([]interface{}, len(dataSlice)) 39 | for i, d := range dataSlice { 40 | interfaceSlice[i] = d 41 | } 42 | ``` -------------------------------------------------------------------------------- /docs/MutexOrChannel.md: -------------------------------------------------------------------------------- 1 | # Use a sync.Mutex or a channel? 2 | 3 | One of Go's mottos is _"Share memory by communicating, don't communicate by sharing memory."_ 4 | 5 | That said, Go does provide traditional locking mechanisms in the sync package. Most locking issues can be solved using either channels or traditional locks. 6 | 7 | So which should you use? 8 | 9 | Use whichever is most expressive and/or most simple. 10 | 11 | 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 sync.Mutex 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. 12 | 13 | As a general guide, though: 14 | 15 | | **Channel** | **Mutex** | 16 | |:------------|:----------| 17 | | passing ownership of data,
distributing units of work,
communicating async results | caches,
state | 18 | 19 | If you ever find your sync.Mutex locking rules are getting too complex, ask yourself whether using channel(s) might be simpler. 20 | 21 | ### Wait Group 22 | 23 | Another important synchronisation primitive is sync.WaitGroup. These allow co-operating goroutines to collectively wait for a threshold event before proceeding independently again. This is useful typically in two cases. 24 | 25 | Firstly, when 'cleaning up', a sync.WaitGroup can be used to ensure that all goroutines - including the main one - wait before all terminating cleanly. 26 | 27 | The second more general case is of a cyclic algorithm that involves a set of goroutines that all work independently for a while, then all wait on a barrier, before proceeding independently again. This pattern might be repeated many times. Data might be exchanged at the barrier event. This strategy is the basis of [Bulk Synchronous Parallelism](https://en.wikipedia.org/wiki/Bulk_synchronous_parallel) (BSP). 28 | 29 | Channel communication, mutexes and wait-groups are complementary and can be combined. 30 | 31 | ### More Info 32 | 33 | * Channels in Effective Go: http://golang.org/doc/effective_go.html#channels 34 | * The sync package: http://golang.org/pkg/sync/ -------------------------------------------------------------------------------- /docs/NonEnglish.md: -------------------------------------------------------------------------------- 1 | Some of this documentation may be out of date. 2 | 3 | ## Belarusian - Беларуская 4 | 5 | * [faq-be](http://www.designcontest.com/show/faq-be) - Frequently Asked Questions. 6 | 7 | ## Brazilian Portuguese - Português brasileiro 8 | 9 | * [A Tour of Go](http://go-tour-br.appspot.com/) 10 | * [golangbr.org](http://golangbr.org/) - Go documentation and news. 11 | 12 | ## Chinese - 中文 13 | 14 | * [A Tour of Go](http://go-tour-zh.appspot.com/) 15 | * [Go 编程语言](http://zh-golang.appspot.com/) - Chinese Translation of tip.golang.org 16 | * [Go编程语言](https://golang-china.appspot.com/) ([参与翻译](https://github.com/golang-china)) - Go语言文档翻译(QQ群:368836416). 17 | * [Effective Go and (old) Tutorial](http://code.google.com/p/ac-me/downloads/detail?name=fango.pdf) 18 | 19 | ## Czech - Čeština 20 | 21 | * [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). 22 | 23 | ## French - Français 24 | 25 | * [golang-france](http://code.google.com/p/golang-france/) - Go documentation. 26 | 27 | ## German - Deutsch 28 | 29 | * [Deutschsprachige Go Themenseite - German Go resource page](http://www.hweidner.de/golang) 30 | 31 | ## Japanese - 日本語 32 | 33 | * [A Tour of Go](http://go-tour-jp.appspot.com/) 34 | * [CodeReviewComments](https://qiita.com/knsh14/items/8b73b31822c109d4c497) 35 | 36 | 37 | ## Korean - 한국어 38 | 39 | * [A Tour of Go](http://go-tour-kr.appspot.com) 40 | * [golang-kr wiki](http://github.com/golang-kr/golang-doc/wiki) - Korean Translation of golang.org/doc 41 | 42 | ## Russian - русский язык 43 | 44 | * [Effective Go](https://github.com/Konstantin8105/Effective_Go_RU/blob/master/README.md) 45 | * [Contribution Guide](https://github.com/Konstantin8105/Contribution_Guide_RU) 46 | 47 | ## Spanish - español 48 | * [Video course: Go Course from 0 to 100](https://www.youtube.com/watch?v=7SIIyt5-XK0&list=PLl_hIu4u7P64MEJpR3eVwQ1l_FtJq4a5g) 49 | 50 | ## Turkish - Türkçe 51 | 52 | * [A Tour of Go](https://go-tour-turkish.appspot.com) 53 | 54 | ## Vietnamese - Tiếng Việt 55 | 56 | * [A Tour of Go](http://go-tour-vi.appspot.com/) 57 | 58 | ## Uzbek — Ўзбекча 59 | 60 | * [A Tour of Go](http://go-tour-uz.appspot.com/) -------------------------------------------------------------------------------- /docs/CommitMessage.md: -------------------------------------------------------------------------------- 1 | # Commit messages 2 | 3 | Commit messages, also known as CL (changelist) descriptions, for Go repos should be formatted as follows: 4 | 5 | ``` 6 | net/http: frob the quux before blarfing 7 | 8 | Fixes #nnnn 9 | ``` 10 | 11 | Notably, 12 | 13 | * the package name goes before the colon 14 | * the part after the colon uses the verb tense + phrase that completes the blank in, *"This change modifies Go to ___________"* 15 | * lowercase verb after the colon 16 | * no trailing period 17 | * keep the subject (first line) as short as possible. ideally under 76 characters or shorter. 18 | * keep the body wrapped too, also max 76, unless it's really needed (ASCII art, table, or long link) 19 | * the Fixes/Updates line should be after the body with a blank newline separating the two 20 | * no Markdown 21 | * we **do not** use `Signed-off-by` lines in Go. Please don't add them. Our Gerrit server & GitHub bots enforce CLA compliance instead. 22 | 23 | If it's not a complete fix and more is coming, use: 24 | 25 | ``` 26 | Updates #nnn 27 | ``` 28 | 29 | ... instead of `Fixes`. Don't use the other GitHub-supported verbs. 30 | 31 | # Other repos 32 | 33 | For non-"go" repos ("crypto", "tools", "net", etc), the subject is still the name of the package, but you need to fully-qualify the issue number with the GitHub org/repo syntax: 34 | 35 | ``` 36 | cipher/rot13: add new super secure cipher 37 | 38 | Fixes golang/go#1234 39 | ```` 40 | 41 | Notably, the first line subject should **not** contain the `x/crypto/` prefix. We only do that for the issue tracker. 42 | 43 | # Non-normative references 44 | 45 | - [Please heed my plea and write good CL descriptions for Go—and for any other project you work on.](https://groups.google.com/d/msg/golang-dev/6M4dmZWpFaI/SyU5Sl4zZLYJ) 46 | - [The CL description is a public document that explains to the future what has been done and why.](https://groups.google.com/d/msg/golang-dev/s07ZUR8ZDHo/i-rIsknbAwAJ) 47 | 48 | # GitHub Pull Requests 49 | 50 | If you're using GitHub Pull Requests, your commit message is constructed by GerritBot based on your 51 | PR's title & description. See https://github.com/golang/go/wiki/GerritBot#how-does-gerritbot-determine-the-final-commit-message 52 | 53 | If somebody asks you to modify your commit message, you'll need to modify your PR. -------------------------------------------------------------------------------- /docs/PriorDiscussion.md: -------------------------------------------------------------------------------- 1 | # Prior Discussion 2 | 3 | ## Background 4 | 5 | This page links to prior discussion on various topics. 6 | 7 | The page complements the [official FAQ](https://golang.org/doc/faq). While the official FAQ contains things which are frequently asked and contains answers, this page contains things that have been repeatedly asked, but maybe not frequently, and only needs to link to one or more previous threads. Over time, these entries may graduate to entries in the official FAQ. 8 | 9 | **Editors:** When editing this page, please don't change the titles of sections, as that breaks the #anchors in URLs. You can rearrange, though. Feel free to add entries at will. There is no requirement for code or English review here. 10 | 11 | ## Asked Questions & Prior Discussion 12 | 13 | ### Panics on sends or closes of closed channel 14 | 15 | See https://github.com/golang/go/issues/11344#issuecomment-117862884 16 | 17 | ### Thread-local, Goroutine-local storage 18 | 19 | TODO 20 | 21 | ### Add explicit int-to-bool conversions 22 | 23 | Rejected, see 24 | https://github.com/golang/go/issues/9367#issuecomment-143128337 25 | 26 | ### Add mechanism to silence vet warnings 27 | 28 | Rejected, see discussion in https://github.com/golang/go/issues/17058 29 | 30 | ### Add vet warning for unused function arguments 31 | 32 | Rejected, see https://github.com/golang/go/issues/7892#issuecomment-66094282 33 | 34 | ### Make go get more verbose / add a progress bar 35 | 36 | Rejected, see 37 | https://github.com/golang/go/issues/17959 38 | https://github.com/golang/go/issues/18388#issuecomment-268315634 39 | 40 | ### Shorten error handling / return sugar 41 | 42 | Rejected, see 43 | https://github.com/golang/go/issues/16225 44 | 45 | ### Support symlinks in go toolchain / environment variables 46 | 47 | Rejected, see 48 | https://github.com/golang/go/issues/15507 49 | 50 | ### Make unused imports/variables a warning, not an error 51 | 52 | Rejected. 53 | 54 | ### Add warnings to the Go compiler 55 | 56 | Rejected. 57 | 58 | ### Weak references 59 | 60 | Unlikely to be added. See discussion at https://groups.google.com/forum/#!topic/golang-nuts/PYWxjT2v6ps, and https://groups.google.com/forum/?pli=1#!topic/golang-nuts/MMWXRANh0-g which points out that `sync.Pool` is a specific form of weak reference. -------------------------------------------------------------------------------- /docs/ProviderIntegration.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | 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. 4 | 5 | # Details 6 | 7 | | PaaS | Repository | Quickstart Guide | 8 | |:-----|:-----------|:-----------------| 9 | | [Google App Engine](http://developers.google.com/appengine/) | https://github.com/GoogleCloudPlatform/appengine-plus-go | https://developers.google.com/appengine/training/go-plus-appengine/ | 10 | | [Azure](http://www.azure.com/) | https://github.com/wadewegner/azure-website-go-builder | http://www.wadewegner.com/2015/01/creating-a-go-site-extension-and-resource-template-for-azure/ | 11 | | [IBM BlueMix](http://www.ibm.com/bluemix) | | http://www.ibm.com/developerworks/cloud/library/cl-bluemix-go-app/ | 12 | | [CloudBees](http://www.cloudbees.com) | https://github.com/CloudBees-community/golang-clickstart | | 13 | | [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/ | 14 | | [dotCloud](http://www.dotcloud.com) | https://github.com/kencochrane/golang-on-dotcloud | | 15 | | [AWS Elastic Beanstalk](https://aws.amazon.com/en/elasticbeanstalk/) | https://github.com/sqs/go-elasticbeanstalk | | 16 | | [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 | 17 | | [OpenShift](http://openshift.redhat.com) | https://github.com/gcmurphy/golang-openshift | | 18 | | [Stackato](http://www.activestate.com/stackato) | https://github.com/kr/heroku-buildpack-go | http://docs.stackato.com/user/deploy/languages/go.html | 19 | | [Tsuru](http://www.tsuru.io/) | | http://docs.tsuru.io/en/latest/apps/quickstart/go.html | 20 | | [Cocaine](http://tech.yandex.com/cocaine/) | http://github.com/cocaine https://github.com/3Hren/cocaine-core https://github.com/3Hren/cocaine-plugins https://github.com/cocaine/cocaine-framework-go | https://github.com/cocaine/cocaine-vagrant and https://github.com/3Hren/cocaine-core | 21 | | [GE Predix](https://www.predix.io/) | https://github.com/geaviation/goboot-starter | https://www.predix.io/resources/tutorials/journey.html | 22 | -------------------------------------------------------------------------------- /docs/TableDrivenTests.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 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. 3 | 4 | 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. 5 | 6 | ## Example of a table driven test 7 | 8 | Here is a good example from the testing code for the ` fmt ` package ( http://golang.org/pkg/fmt/ ): 9 | 10 | ```go 11 | var flagtests = []struct { 12 | in string 13 | out string 14 | }{ 15 | {"%a", "[%a]"}, 16 | {"%-a", "[%-a]"}, 17 | {"%+a", "[%+a]"}, 18 | {"%#a", "[%#a]"}, 19 | {"% a", "[% a]"}, 20 | {"%0a", "[%0a]"}, 21 | {"%1.2a", "[%1.2a]"}, 22 | {"%-1.2a", "[%-1.2a]"}, 23 | {"%+1.2a", "[%+1.2a]"}, 24 | {"%-+1.2a", "[%+-1.2a]"}, 25 | {"%-+1.2abc", "[%+-1.2a]bc"}, 26 | {"%-1.2abc", "[%-1.2a]bc"}, 27 | } 28 | 29 | func TestFlagParser(t *testing.T) { 30 | var flagprinter flagPrinter 31 | for _, tt := range flagtests { 32 | s := Sprintf(tt.in, &flagprinter) 33 | if s != tt.out { 34 | t.Errorf("Sprintf(%q, &flagprinter) => %q, want %q", tt.in, s, tt.out) 35 | } 36 | } 37 | } 38 | ``` 39 | 40 | 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. 41 | 42 | 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. 43 | 44 | ## References 45 | 46 | * http://golang.org/doc/code.html#Testing 47 | * http://golang.org/doc/faq#assertions 48 | * http://golang.org/doc/faq#testing_framework 49 | * http://golang.org/pkg/testing/ -------------------------------------------------------------------------------- /docs/ChromeOS.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | This tutorial will show you how to install/build/run go on chrome OS. I have tested this using a Chromebook Pixel, however I do not have any other types of Chromebooks. However, this should work as long as you install the corresponding Linux package for your processor. 3 | 4 | # Requirements 5 | Your Chromebook 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 Chromebooks. Note that enabling developer mode reduces the security guarantees offered by Chrome OS. 6 | 7 | # Install Go 8 | First download the latest version of Go for Linux-amd64 from the [Go Downloads page](http://golang.org/dl/) after that open a shell by hitting (Crtl+alt+t) and typing in "shell" then hit enter. Then extract it using the following command. 9 | 10 | ``` 11 | sudo tar -C /usr/local -xzf ~/Downloads/FILENAMEHERE 12 | ``` 13 | 14 | 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. 15 | 16 | # Create a Workspace 17 | To keep this simple just create a folder called "gocode" in your downloads folder. Also create a folder called "src" inside. 18 | 19 | # Set Paths & Exec 20 | 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. 21 | ``` 22 | export PATH=$PATH:/usr/local/go/bin 23 | export GOPATH=~/Downloads/go 24 | export PATH=$PATH:$GOPATH/bin 25 | sudo mount -i -o remount,exec /home/chronos/user/ 26 | ``` 27 | This will allow you to run your go object files in your shell. 28 | 29 | # Test If It Worked 30 | 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. 31 | ```go 32 | package main 33 | 34 | import "fmt" 35 | 36 | func main() { 37 | fmt.Printf("Hello, chrome os\n") 38 | } 39 | ``` -------------------------------------------------------------------------------- /docs/Errors.md: -------------------------------------------------------------------------------- 1 | # Errors 2 | 3 | Errors are indicated by returning an `error` as an additional return value from a function. A `nil` value means that there was no error. 4 | 5 | ` 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`: 6 | 7 | ``` 8 | if failure { 9 | return errors.New("inverse tachyon pulse failed") 10 | } 11 | ``` 12 | 13 | Error strings should not start with a capital letter because they'll often be prefixed before printing: 14 | 15 | ``` 16 | err := TryInverseTachyonPulse() 17 | if err != nil { 18 | fmt.Printf("failed to solve problem: %s\n", err) 19 | } 20 | ``` 21 | 22 | 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. 23 | 24 | `io.EOF` is a special value that signals the end of a stream. You can compare error values directly against io.EOF. 25 | 26 | If you want to carry extra data with the error, you can use a new type: 27 | 28 | ``` 29 | type ParseError struct { 30 | Line, Col int 31 | } 32 | 33 | func (p ParseError) Error() string { 34 | return fmt.Sprintf("parse error on line %d, column %d", p.Line, p.Col) 35 | } 36 | ``` 37 | 38 | Calling code would test for a special type of `error` by using a type switch: 39 | 40 | ``` 41 | switch err := err.(type) { 42 | case ParseError: 43 | PrintParseError(err) 44 | } 45 | ``` 46 | 47 | ## Naming 48 | 49 | Error types end in `"Error"` and error variables start with `"Err"`: 50 | 51 | ``` 52 | package somepkg 53 | 54 | // ParseError is type of error returned when there's a parsing problem. 55 | type ParseError struct { 56 | Line, Col int 57 | } 58 | 59 | var ErrBadAction = errors.New("somepkg: a bad action was performed") 60 | 61 | // ----- 62 | 63 | package foo 64 | 65 | func foo() { 66 | res, err := somepkgAction() 67 | if err != nil { 68 | if err == somepkg.ErrBadAction { 69 | } 70 | if pe, ok := err.(*somepkg.ParseError); ok { 71 | line, col := pe.Line, pe.Col 72 | // .... 73 | } 74 | } 75 | } 76 | ``` 77 | 78 | ## References 79 | 80 | * Errors (specification): http://golang.org/ref/spec#Errors 81 | * Package `errors`: http://golang.org/pkg/errors/ 82 | * Type switches: http://golang.org/doc/go_spec.html#TypeSwitchStmt -------------------------------------------------------------------------------- /docs/SettingGOPATH.md: -------------------------------------------------------------------------------- 1 | # Setting `GOPATH` 2 | 3 | The `GOPATH` environment variable specifies the location of your workspace. If no `GOPATH` is set, it is assumed to be `$HOME/go` on Unix systems and `%USERPROFILE%\go` on Windows. If you want to use a custom location as your workspace, you can set the `GOPATH` environment variable. This page explains how to set this variable on various platforms. 4 | 5 | 6 | - [Unix systems](#unix-systems) 7 | * [Bash](#bash) 8 | * [Zsh](#zsh) 9 | - [Windows](#windows) 10 | 11 | # Unix systems 12 | 13 | `GOPATH` can be any directory on your system. In Unix examples, we will set it to `$HOME/go` (since Go 1.8, it's a default `GOPATH` on Unix-like systems). Note that `GOPATH` must not be the same path as your Go installation. Another common setup is to set `GOPATH=$HOME`. 14 | 15 | ## Bash 16 | 17 | Edit your `~/.bash_profile` to add the following line: 18 | ```bash 19 | export GOPATH=$HOME/go 20 | ``` 21 | 22 | Save and exit your editor. Then, source your `~/.bash_profile`. 23 | ```bash 24 | source ~/.bash_profile 25 | ``` 26 | 27 | > Note: Set the GOBIN path to generate a binary file when `go install` is run. 28 | > ```bash 29 | > export GOBIN=$HOME/go/bin 30 | > ``` 31 | 32 | ## Zsh 33 | 34 | Edit your `~/.zshrc` file to add the following line: 35 | 36 | ```bash 37 | export GOPATH=$HOME/go 38 | ``` 39 | Save and exit your editor. Then, source your `~/.zshrc`. 40 | ```bash 41 | $ source ~/.zshrc 42 | ``` 43 | 44 | ## fish 45 | 46 | ```bash 47 | set -x -U GOPATH $HOME/go 48 | ``` 49 | > The `-x` is used to specify that this variable should be exported 50 | > and the `-U` makes this a universal variable, available to all sessions and 51 | > persistent 52 | 53 | To set the GOBIN path: 54 | 55 | ```bash 56 | set -x -U GOBIN $GOPATH/bin 57 | ``` 58 | 59 | # Windows 60 | 61 | Your workspace can be located wherever you like, 62 | but we'll use `C:\go-work` in this example. 63 | 64 | __NOTE:__ that `GOPATH` must not be the same path as your Go installation. 65 | 66 | * Create folder at `C:\go-work`. 67 | * Right click on "Start" and click on "Control Panel". Select "System and Security", then click on "System". 68 | * From the menu on the left, select the "Advanced systems settings". 69 | * Click the "Environment Variables" button at the bottom. 70 | * Click "New" from the "User variables" section. 71 | * Type `GOPATH` into the "Variable name" field. 72 | * Type `C:\go-work` into the "Variable value" field. 73 | * Click OK. 74 | 75 | ## Windows 10 76 | There is a faster way to edit `Environment Variables` with search 77 | * Left click on "Search" and type `env` or `environment`. select `Edit environment variables for your account` 78 | * and follow step above -------------------------------------------------------------------------------- /docs/DashboardBuilders.md: -------------------------------------------------------------------------------- 1 | ## Builders 2 | 3 | Build configs (at the top) and host configs (bottom) are listed here: 4 | 5 | http://farmer.golang.org/builders 6 | 7 | A builder runs on a certain host type. (e.g. `linux-386-387` is a build type. It runs on `host-linux-kubestd`, a Kubernetes-based linux/amd64 host) 8 | 9 | They come from the file https://github.com/golang/build/blob/master/dashboard/builders.go 10 | 11 | For design details about the coordinator, see http://golang.org/s/builderplan 12 | 13 | # How to set up a builder 14 | 1. talk to golang-dev@ to get a builder host type & hash (they can get one from e.g. https://build-dot-golang-org.appspot.com/key?builder=host-foo-bar), and put that in ` ~/.gobuildkey` or `~/.gobuildkey-host-foo-bar` or the file pointed to be env var `$GO_BUILD_KEY_PATH`. 15 | 1. go get golang.org/x/build/cmd/buildlet 16 | 1. Run the buildlet in a loop or under systemd: `while true; do buildlet -coordinator=farmer.golang.org -reverse-type=host-foo-bar -reboot=false; done` 17 | 1. Verify you can see the host registered at https://farmer.golang.org/#pools in the "Reverse pool machine detail" section and "Reverse pool summary". 18 | 1. Add a builder type to https://github.com/golang/build/blob/master/dashboard/builders.go (see the `addBuilder` lines). Run tests. Send the CL. 19 | 1. Have golang-dev deploy it. 20 | 21 | ## Old-style builders 22 | 23 | Older-style builders are listed below. These builders are configured and run manually. The bug https://github.com/golang/go/issues/21191 tracks migrating the remaining ones over to the new system. 24 | 25 | | **title** | **description** | **owner** | **notes** | 26 | |:----------|:----------------|:----------|:----------| 27 | | nacl-arm-cheney | Raspberry Pi 3 | @davecheney | | 28 | | openbsd-arm | SolidRun CuBox-i4Pro, ARM Cortex A9 R2 792 MHz, 2GB RAM | @4a6f656c - Joel Sing | | 29 | | plan9-arm | Raspberry Pi 3 Model B | @0intro - David du Colombier | Plan 9 from Bell Labs | 30 | | plan9-amd64-9front | VM | @0intro - David du Colombier | 9front | 31 | 32 | # Builder Requirements 33 | * internet connection (at least be able to access Google and http://build.golang.org) 34 | * preferably with two or more (V)CPUs, as at least one test (` sync/atomic ` requires ` runtime.NumCPU() > 1 ` to test more completely) 35 | * at least 512MiB of memory (1GB or more highly recommended. 512MB might need a small `GOGC` setting to avoid thrashing.) 36 | 37 | # Restrictions 38 | * 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. 39 | 40 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

:page_with_curl: learn golang kr

2 |

golang-kr

3 |

golang을 시작하며 필요한 모든 정보를 취합하는 리포지토리 입니다.

4 |

:raised_hands: golang 빠른 가이드

5 | 6 | ## 시작하며 7 | 8 | 이 리포지토리는 한국에 golang 가이드가 너무 없는 것에 우울하여 귀차니즘을 무릎쓰고 만들어졌습니다. 9 | 10 | 아시는분들은 아시겠지만 국내 golang 커뮤니티가 많이 활성화되어 있지 않습니다. 11 | 12 | 이런 작은 프로젝트를 시작으로 다른 Gopher분들도 기여와 커뮤니티에 많이 참여하셨으면 좋겠습니다. 13 | 14 | ## 목차 15 | 16 | + [Go를 시작하며](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#go를-시작하며) 17 | + [Go 작업하기](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#go로-작업하기) 18 | + [Go에 대해 더 알아보기](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#go에-대해-더-알아보기) 19 | + [Go 커뮤니티](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#go-커뮤니티) 20 | + [Go 툴체인](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#go-툴체인) 21 | + [Go의 또 다른 위키들](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#go의-또-다른-위키들) 22 | + [Go로 동작하는 서비스들](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#go로-동작하는-서비스들) 23 | + [Go를 이용한 프로덕션에서의 문제해결](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#go를-이용한-프로덕션에서의-문제해결) 24 | + [Go 프로젝트에 기여](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#go-프로젝트에-기여) 25 | + [플랫폼 관련 정보](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#플랫폼-관련-정보) 26 | + [릴리즈 관련 정보](https://github.com/KennethanCeyer/learn-golang-kr/wiki/#릴리즈-관련-정보) 27 | 28 | ## 기여 29 | 30 | ### 규칙 31 | 32 | 1. 문서는 GitHub Wiki에서 관리합니다. 33 | 2. 참고한 문서는 그 출처를 명시하도록 합니다. 34 | 3. 기여는 GitHub의 Pull Request를 이용하여 진행합니다. 35 | 4. 문서는 되도록 간결체를 사용합니다. 36 | 5. 스크린샷이 필요한 경우 IDE는 `JetBrains GoLand` 스크린샷은 자유롭게 올리되 Pull Request에 기록합니다. 37 | 6. [GPG sign](https://help.github.com/articles/signing-commits-using-gpg/)이 된 커밋을 올려주시기 바랍니다. 38 | 39 | ### 문서 구조 40 | 41 | 1. 우리는 [GitHub WIKI](https://github.com/KennethanCeyer/learn-golang-kr/wiki)를 이용해서 문서화를 진행하고 있습니다. 42 | 2. 업데이트 된 위키는 해당 리포지토리의 `subtree`로 구성되어 업데이트 됩니다. 43 | 3. 그리고 우리는 [마법](https://github.com/QingWei-Li/docsify)을 이용해서 그렇게 업데이트 한 `readme.md`를 [GitHub Page](https://www.pigno.se/barn/learn-golang-kr/docs/#/Home)로 출판합니다. 44 | 4. 추후 규모가 커지면 별도의 도메인으로 vhost 설정하여 url을 축약할 예정입니다. 45 | 46 | ## 로드맵 47 | 48 | - [ ] [golang/go Wiki](https://github.com/golang/go/wiki) 번역 49 | - [ ] [golang.org/doc/code.html](https://golang.org/doc/code.html) 번역 50 | - [ ] [golang.org/doc/effective_go.html](https://golang.org/doc/effective_go.html) 번역 51 | - [ ] Go 테스트 베스트프렉티스 52 | - [ ] 쉬운 설치가이드 작성 53 | - [ ] 네이밍 컨벤션 작성 54 | - [ ] 라이브러리 배포 및 관리 방법 작성 55 | - [ ] Go 엔터프라이즈 아키텍처 설계 방법 작성 56 | - [ ] Go를 사용한 제품들 57 | -------------------------------------------------------------------------------- /docs/SQLDrivers.md: -------------------------------------------------------------------------------- 1 | # SQL database drivers 2 | 3 | The database/sql and database/sql/driver packages are designed for using databases from Go and implementing database drivers, respectively. 4 | 5 | See the design goals doc: 6 | 7 | > http://golang.org/src/pkg/database/sql/doc.txt 8 | 9 | # Drivers 10 | 11 | Drivers for Go's sql package include: 12 | 13 | * **Apache Ignite/GridGain**: https://github.com/amsokol/go-ignite-client 14 | * **Apache Phoenix/Avatica**: https://github.com/Boostport/avatica 15 | * **ClickHouse** (uses [native TCP interface](https://clickhouse.yandex/docs/en/interfaces/tcp.html)): https://github.com/kshvakov/clickhouse 16 | * **ClickHouse** (uses [HTTP API](https://clickhouse.yandex/docs/en/interfaces/http_interface.html)): https://github.com/mailru/go-clickhouse 17 | * **Couchbase N1QL**: https://github.com/couchbase/go_n1ql 18 | * **DB2**: https://bitbucket.org/phiggins/db2cli 19 | * **DB2 LUW**: https://github.com/asifjalil/cli 20 | * **Firebird SQL**: https://github.com/nakagami/firebirdsql 21 | * **MS ADODB**: https://github.com/mattn/go-adodb 22 | * **MS SQL Server** (pure go): https://github.com/denisenkom/go-mssqldb 23 | * **MS SQL Server** (uses cgo): https://github.com/minus5/gofreetds 24 | * **MySQL**: https://github.com/ziutek/mymysql ` [*] ` 25 | * **MySQL**: https://github.com/go-sql-driver/mysql/ ` [*] ` 26 | * **ODBC**: https://bitbucket.org/miquella/mgodbc 27 | * **ODBC**: https://github.com/alexbrainman/odbc 28 | * **Oracle**: https://github.com/mattn/go-oci8 29 | * **Oracle**: https://github.com/rana/ora 30 | * **QL**: http://godoc.org/github.com/cznic/ql/driver 31 | * **Postgres** (pure Go): https://github.com/lib/pq ` [*] ` 32 | * **Postgres** (uses cgo): https://github.com/jbarham/gopgsqldriver 33 | * **Postgres** (pure Go): https://github.com/jackc/pgx ` [**] ` 34 | * **SAP HANA** (pure go): https://github.com/SAP/go-hdb 35 | * **Snowflake** (pure Go): https://github.com/snowflakedb/gosnowflake 36 | * **SQLite** (uses cgo): https://github.com/mattn/go-sqlite3 ` [*] ` 37 | * **SQLite** (uses cgo): https://github.com/gwenn/gosqlite - Supports SQLite dynamic data typing 38 | * **SQLite** (uses cgo): https://github.com/mxk/go-sqlite 39 | * **SQLite**: (uses cgo): https://github.com/rsc/sqlite 40 | * **Sybase SQL Anywhere**: https://github.com/a-palchikov/sqlago 41 | * **Vitess**: https://godoc.org/github.com/youtube/vitess/go/vt/vitessdriver 42 | * **YQL (Yahoo! Query Language)**: https://github.com/mattn/go-yql 43 | 44 | Drivers marked with ` [*] ` are both included in and pass the compatibility test suite at https://github.com/bradfitz/go-sql-test. 45 | Drivers marked with ` [**] ` pass the compatibility test suite but are not currently included in it. -------------------------------------------------------------------------------- /docs/CommonMistakes.md: -------------------------------------------------------------------------------- 1 | Table of Contents 2 | ================= 3 | 4 | + [Introduction](#introduction) 5 | + [Using goroutines on loop iterator variables](#using-goroutines-on-loop-iterator-variables) 6 | 7 | # Introduction 8 | 9 | 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. 10 | 11 | # Using goroutines on loop iterator variables 12 | 13 | When iterating in Go, one might also be tempted to use goroutines to process data in parallel. For example, you might write the following code: 14 | ```go 15 | for val := range values { 16 | go val.MyMethod() 17 | } 18 | ``` 19 | 20 | or if you wanted to process values coming in from a channel in their own goroutines, you might write something like this, using a closure: 21 | 22 | ```go 23 | for val := range values { 24 | go func() { 25 | fmt.Println(val) 26 | }() 27 | } 28 | ``` 29 | 30 | The above for loops might not do what you expect because their ` val ` variable 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. 31 | 32 | The proper way to write that closure loop is: 33 | ```go 34 | for val := range values { 35 | go func(val interface{}) { 36 | fmt.Println(val) 37 | }(val) 38 | } 39 | ``` 40 | 41 | 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. 42 | 43 | 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: 44 | 45 | ```go 46 | for i := range valslice { 47 | val := valslice[i] 48 | go func() { 49 | fmt.Println(val) 50 | }() 51 | } 52 | ``` 53 | 54 | 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. 55 | 56 | ```go 57 | for i := 1; i <= 10; i++ { 58 | func() { 59 | fmt.Println(i) 60 | }() 61 | } 62 | ``` 63 | 64 | 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. 65 | 66 | http://golang.org/doc/go_faq.html#closures_and_goroutines -------------------------------------------------------------------------------- /docs/OpenBSD.md: -------------------------------------------------------------------------------- 1 | # Go on OpenBSD 2 | 3 | Go is available within the OpenBSD ports tree collection since OpenBSD 5.2. It is marked as i386- and amd64- only. See [`ports/lang/go`](http://ports.su/lang/go) for details. 4 | 5 | | **OpenBSD release** | **Go in ports** | 6 | |:--------------------|:--------------------| 7 | | 6.2 (Oct 9, 2017) | go-1.9 | 8 | | 6.1 (Apr 11, 2017) | go-1.8 | 9 | | 6.0 (Sep 1, 2016) | go-1.6.3 | 10 | | 5.9 (Mar 29, 2016) | go-1.5.4 | 11 | | 5.8 (Oct 18, 2015) | go-1.4.2 | 12 | | 5.7 (May 1, 2015) | go-1.4.1 | 13 | | 5.6 (Nov 1, 2014) | go-1.3p0 | 14 | 15 | ## Building from source 16 | 17 | | **Kernel version** | **Architectures** | **Initial support version** | **Final support version** | 18 | |:-------------------|:------------------|:----------------------------|:--------------------------| 19 | | 6.2 | amd64, arm, 386 | Go 1.9 | | 20 | | 6.1 | amd64, arm, 386 | Go 1.8 | Go 1.10.1 | 21 | | 6.0 | amd64, 386 | Go 1.4.1 _*_ | Go 1.10.1 | 22 | | 6.0 | arm | Go 1.5 | Go 1.10.1 | 23 | | 5.9 | amd64, 386 | Go 1.4.1 _*_ | Go 1.8.7 | 24 | | 5.9 | arm | Go 1.5 | Go 1.8.7 | 25 | | 5.6 through 5.8 | amd64, 386 | Go 1.4.1 _*_ | Go 1.7.6 | 26 | | 5.5 | amd64, 386 | Go 1.3 _*_ | Go 1.7.6 | 27 | | 5.0 through 5.4 | amd64, 386 | Go 1 | Go 1.2.2 | 28 | 29 | _*_ Go 1.5 or above is recommended. 30 | 31 | ## Longterm support 32 | 33 | Go aims to support the two most recent OpenBSD releases, because OpenBSD officially supports only the two most recent releases, and makes a best-effort attempt to maintain ABI support in consecutive releases. 34 | 35 | ## ulimits (` /etc/login.conf `) 36 | 37 | Edit `/etc/login.conf` so that the staff class has the proper 38 | settings. The following is a working example of the staff class: 39 | ``` 40 | staff:\ 41 | :datasize-cur=infinity:\ 42 | :datasize-max=infinity:\ 43 | :datasize=infinity:\ 44 | :openfiles-cur=4096:\ 45 | :maxproc-max=512:\ 46 | :maxproc-cur=512:\ 47 | :ignorenologin:\ 48 | :requirehome@:\ 49 | :tc=default: 50 | ``` 51 | 52 | If the database file `/etc/login.conf.db` exists, you need to rebuild it with: 53 | ``` 54 | # cap_mkdb /etc/login.conf 55 | ``` 56 | 57 | Ensure that the user you intend to build Go with is in the `staff` login class: 58 | ``` 59 | # usermod -L staff your_username_here 60 | ``` -------------------------------------------------------------------------------- /docs/WindowsCrossCompiling.md: -------------------------------------------------------------------------------- 1 | # Building windows go programs on linux 2 | 3 | See [here](https://golang.org/doc/install/source#environment) for available `GOOS` and `GOARCH` values. 4 | 5 | ## Go version >= 1.5 6 | 7 | Since Go version 1.5 cross-compiling has become very easy. Try it out with the code below. More can be found at this blog post by [Dave Cheney][1]. 8 | 9 | [1]: http://dave.cheney.net/2015/08/22/cross-compilation-with-go-1-5 10 | 11 | ```go 12 | $ cat hello.go 13 | package main 14 | 15 | import "fmt" 16 | 17 | func main() { 18 | fmt.Printf("Hello\n") 19 | } 20 | $ GOOS=windows GOARCH=386 go build -o hello.exe hello.go 21 | ``` 22 | 23 | You can now run `hello.exe` on a Windows machine near you. 24 | 25 | Note that the command above will silently rebuild most of standard library, and for this reason will be quite slow. To speed-up the process, you can install all the windows-amd64 standard packages on your system with 26 | 27 | ``` 28 | GOOS=windows GOARCH=amd64 go install 29 | ``` 30 | 31 | ## Older Go version (<1.5) 32 | 33 | I use linux/386, but, I suspect, this procedure will apply to other host platforms as well. 34 | 35 | Preparation (if needed): 36 | ```sh 37 | sudo apt-get install gcc 38 | export go env GOROOT 39 | ``` 40 | 41 | First step is to build host version of go: 42 | 43 | ```sh 44 | cd $GOROOT/src 45 | sudo -E GOOS=windows GOARCH=386 PATH=$PATH ./make.bash 46 | ``` 47 | 48 | Next you need to build the rest of go compilers and linkers. I have small program to do that: 49 | 50 | ```sh 51 | $ cat ~/bin/buildcmd 52 | #!/bin/sh 53 | set -e 54 | for arch in 8 6; do 55 | for cmd in a c g l; do 56 | go tool dist install -v cmd/$arch$cmd 57 | done 58 | done 59 | exit 0 60 | ``` 61 | 62 | Last step is to build windows versions of standard commands and libraries. I have small script for that too: 63 | 64 | ```sh 65 | $ cat ~/bin/buildpkg 66 | #!/bin/sh 67 | if [ -z "$1" ]; then 68 | echo 'GOOS is not specified' 1>&2 69 | exit 2 70 | else 71 | export GOOS=$1 72 | if [ "$GOOS" = "windows" ]; then 73 | export CGO_ENABLED=0 74 | fi 75 | fi 76 | shift 77 | if [ -n "$1" ]; then 78 | export GOARCH=$1 79 | fi 80 | cd $GOROOT/src 81 | go tool dist install -v pkg/runtime 82 | go install -v -a std 83 | ``` 84 | 85 | I run it like that: 86 | 87 | ```sh 88 | $ ~/bin/buildpkg windows 386 89 | ``` 90 | 91 | 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. 92 | 93 | Now we're ready to build our windows executable: 94 | 95 | ```go 96 | $ cat hello.go 97 | package main 98 | 99 | import "fmt" 100 | 101 | func main() { 102 | fmt.Printf("Hello\n") 103 | } 104 | $ GOOS=windows GOARCH=386 go build -o hello.exe hello.go 105 | ``` 106 | 107 | We just need to find Windows computer to run our hello.exe. -------------------------------------------------------------------------------- /docs/CodeTools.md: -------------------------------------------------------------------------------- 1 | An overview of tools that will help improve your Go code 2 | 3 | ## All-in-one 4 | 5 | - [gometalinter](https://github.com/alecthomas/gometalinter) - Automates the installation, configuration and application of `gofmt`, `golint`, `govet` and several other code validation tools. 6 | 7 | ## Code Formatting 8 | 9 | ### Articles 10 | 11 | - [Formatting Go Code with gofmt](http://golangtutorials.blogspot.com/2011/06/formatting-go-code-with-gofmt.html) 12 | 13 | ### Tools 14 | 15 | - [gofmt](https://golang.org/cmd/gofmt/) - Start with the standard Go code formatter 16 | - [golint](https://github.com/golang/lint) - Detects style mistakes in Go code 17 | - [goimports](https://github.com/bradfitz/goimports) - Format code and fix your import statements 18 | 19 | ## Code generation, Templating and Generics 20 | 21 | - [json-to-go](https://mholt.github.io/json-to-go/) - Generate Go structs from JSON. 22 | - [Go gen](http://clipperhouse.github.io/gen/) - Type-driven code generation (generics) 23 | - [gojson](https://github.com/ChimeraCoder/gojson) - Another Go struct generator. 24 | - [gonerics.io](http://bouk.co/blog/idiomatic-generics-in-go/) - Idiomatic Generics in Go 25 | - [gotemplate](https://github.com/ncw/gotemplate) - Package-based templating system for Go 26 | - [sqlgen](https://github.com/drone/sqlgen) - Generate Go code for SQL interactions. 27 | 28 | ## Refactoring 29 | 30 | ### Articles 31 | 32 | - [Refactoring with go fmt](http://spf13.com/post/go-fmt/) 33 | - [gorename - easy refactoring](https://texlution.com/post/gorename/) 34 | - [Refectoring Tools](http://blog.ralch.com/tutorial/golang-tools-refactoring/) - An overview of refactoring tools for Go. 35 | - [Quick renaming with gofmt](http://technosophos.com/2015/09/26/quick-go-hack-renaming-structs.html) 36 | 37 | ### Tools 38 | 39 | - [eg](https://godoc.org/golang.org/x/tools/cmd/eg) - Example-based refactoring tool for Go 40 | - [gofmt](https://golang.org/cmd/gofmt/) - Start with the standard Go code formatter 41 | - [gorename](https://golang.org/x/tools/refactor/rename) - Renaming tool for Go 42 | 43 | ## Error Detection 44 | 45 | ### Articles 46 | 47 | - [Go Inspection Tools](http://blog.ralch.com/tutorial/golang-tools-inspection/) - An overview of tools for Go code inspection. 48 | 49 | ### Tools 50 | 51 | - [AlignCheck, StructCheck, VarCheck](https://github.com/opennota/check/) - A suite of tools for checking your code. 52 | - [errcheck](https://github.com/kisielk/errcheck) - Ensure you check your error conditions. 53 | - [go vet](http://golang.org/cmd/vet/) - Read this first on how to use the `go vet` command. 54 | - [SafeSQL](https://github.com/stripe/safesql) - Protect against unsafe SQL in your code. 55 | 56 | ## Navigation 57 | 58 | - [go oracle - user manual](http://golang.org/s/oracle-user-manual) - A tool for understanding Go code 59 | - [Pythia](https://github.com/fzipp/pythia) - A browser-based UI for the Go Oracle. 60 | 61 | ## Visualization 62 | 63 | - [godegraph](http://github.com/kisielk/godepgraph) - A tool for generating dependency graphs of Go code. 64 | -------------------------------------------------------------------------------- /docs/How-to-ask-for-help.md: -------------------------------------------------------------------------------- 1 | This page gives some hints on how to successfully ask for help in the various [Go support forums][3]. 2 | 3 | ## Before you ask your question 4 | 5 | Before asking for help, please check that you've addressed the following common issues: 6 | 7 | ### Always check all errors 8 | 9 | Always check all errors. It is common to see problems reported related to nil panics due to code like this 10 | ``` 11 | result, err := somefunction() 12 | if err != nil { 13 | log.Println("oops an error happened", err) 14 | // return is missing here 15 | } 16 | // the code then continues to use result which is invalid. 17 | ``` 18 | or 19 | ``` 20 | result, _ := somefunction() 21 | // code uses result which might be invalid 22 | ``` 23 | You should make sure it is clear that your code is correctly handling all error conditions before asking for help. 24 | 25 | Further reading: 26 | - [Error handling and Go][0] 27 | 28 | ### Check that your code is free from data races 29 | 30 | Unexpected runtime panics are often caused by data races in your program. If your program contains a data race you need to address the race before asking for help. 31 | 32 | If your program has good test coverage you can test for races by adding the `-race` flag to your `go test` invocation. 33 | 34 | If your program does not have good test coverage or the crash only happens when running the program, you can build a race enabled version of your program by passing `-race` to your `go build` or `go install` invocation. 35 | 36 | _The behaviour of a Go program with a data race is undefined. There are no safe data races in Go programs._ 37 | 38 | Further reading: 39 | - [Introducing the race detector][1] 40 | 41 | ## Asking questions 42 | 43 | The best way to get help is to show 44 | 45 | 1. **What you did, ideally with a small complete, stand-alone, example.** 46 | If you ran a command, show the command that you ran. If your program failed, provide the source of the program that failed. If the program is too large, or you cannot share the source, instead provide a self contained, runnable example, that demonstrates the problem. 47 | 2. **What you expected to happen.** If you expected the command to complete successfully, say that. If you expected the program to produce a particular output, give an example of the output you expected. 48 | 3. **What happened instead.** 49 | If the command failed, include the full output of the failure, not just a single line that you though was the cause. If the program failed to produce the expected output, include what it did output. 50 | 51 | ## Additional tips 52 | 53 | - If you are posting the output of a command, paste the text, not a screenshot of the text. If it's actually an image, that's ok. 54 | - If you are posting a large amount of output, you may consider using a pastebin or gist service. 55 | - When posting code samples, use the [Go playground][2] (unless it is unavailable in your country). 56 | 57 | [0]: https://blog.golang.org/error-handling-and-go 58 | [1]: https://blog.golang.org/race-detector 59 | [2]: https://play.golang.org 60 | [3]: https://github.com/golang/go/wiki/questions -------------------------------------------------------------------------------- /docs/CompilerOptimizations.md: -------------------------------------------------------------------------------- 1 | # Compiler And Runtime Optimizations 2 | 3 | This page lists optimizations done by the compilers. Note that these are not guaranteed by the language specification. 4 | 5 | ## Interface values 6 | 7 | ### Zero-width types in interface values 8 | 9 | Putting a zero-width type in an interface value doesn't allocate. 10 | 11 | * **gc:** 1.0+ 12 | * **gccgo:** ? 13 | 14 | ### Word-sized value in an interface value 15 | 16 | Putting a word-sized-or-less non-pointer type in an interface value doesn't allocate. 17 | 18 | * **gc:** 1.0-1.3, but *not* in 1.4+ 19 | * **gccgo:** never 20 | 21 | ## `string` and `[]byte` 22 | 23 | ### Map lookup by `[]byte` 24 | 25 | For a map `m` of type `map[string]T` and `[]byte b`, `m[string(b)]` doesn't allocate. (the temporary string copy of the byte slice isn't made) 26 | 27 | * **gc:** 1.4+ 28 | * **gccgo:** ? 29 | 30 | ### `range` over `[]byte`(s) 31 | 32 | Avoiding allocating `[]byte` of a `string` when ranging over the bytes: 33 | 34 | ```go 35 | s := "foo" 36 | for i, c := range []byte(s) { 37 | // ... 38 | } 39 | ``` 40 | 41 | * **gc:** 1.5+ (CL 3790) 42 | * **gccgo:** ? 43 | 44 | ## Escape analysis and Inlining 45 | 46 | Use `-gcflags -m` to observe the result of escape analysis and inlining 47 | decisions for the gc toolchain. 48 | 49 | (TODO: explain the output of `-gcflags -m`). 50 | 51 | ### Escape analysis 52 | 53 | Gc compiler does global escape analysis across function and package boundaries. However, there are lots of cases where it gives up. For example, anything assigned to any kind of indirection (`*p = ...`) is considered escaped. Other things that can inhibit analysis are: function calls, package boundaries, slice literals, subslicing and indexing, etc. Full rules are too complex to describe, so check the `-m` output. 54 | 55 | * **gc:** 1.0+ 56 | * **gccgo:** not yet. 57 | 58 | ### Function Inlining 59 | 60 | Only short and simple functions are inlined. To be inlined a function must contain less than ~40 expressions and does not contain complex things like function calls, loops, labels, closures, `panic`'s, `recover`'s, `select`'s, `switch`'es, etc. 61 | 62 | * **gc:** 1.0+ 63 | * **gccgo:** -O1 and above. 64 | 65 | ## Idioms 66 | 67 | ### Optimized memclr 68 | 69 | For a slice or array s, loops of the form 70 | 71 | ```go 72 | for i := range s { 73 | a[i] = 74 | } 75 | ``` 76 | 77 | are converted into efficient runtime memclr calls. [Issue](https://github.com/golang/go/issues/5373) and [commit](https://golang.org/change/f03c9202c43e0abb130669852082117ca50aa9b1). 78 | 79 | * **gc:** 1.5+ 80 | * **gccgo:** ? 81 | 82 | ## Non-scannable objects 83 | 84 | Garbage collector does not scan underlying buffers of slices, channels and maps when element type does not contain pointers (both key and value for maps). This allows to hold large data sets in memory without paying high price during garbage collection. For example, the following map won't visibly affect GC time: 85 | 86 | ```go 87 | type Key [64]byte // SHA-512 hash 88 | type Value struct { 89 | Name [32]byte 90 | Balance uint64 91 | Timestamp int64 92 | } 93 | m := make(map[Key]Value, 1e8) 94 | ``` 95 | 96 | * **gc:** 1.5+ 97 | * **gccgo:** ? -------------------------------------------------------------------------------- /docs/WindowsBuild.md: -------------------------------------------------------------------------------- 1 | # The Automatic (but unsupported) Way: [winstrap](https://github.com/golang/winstrap) 2 | 3 | The winstrap tool is used by the Go project to turn a fresh Windows VM image into a Windows builder. It installs all necessary dependencies. It's sometimes out of date, though, as it's only updated when we need to update the Windows base image for the [Go continuous build](https://build.golang.org/). 4 | 5 | To use winstrap, download the latest version of winstrap.exe from the [winstrap](https://github.com/golang/winstrap) page and run it. 6 | 7 | It will download some installers to your desktop, which you should run. Just click through; all the defaults are fine. 8 | 9 | Then it will check out Go and place it in c:\Users\%USER%\goroot and build it. 10 | 11 | That's it. 12 | 13 | Note however that winstrap is not supported. It's considered an internal tool used for occasional setup of new Windows builder images and is not actively maintained until we need it ourselves. 14 | 15 | # The Manual Way 16 | 17 | ## Install MinGW/MSYS 18 | 19 | Download and save the latest version of the automated MinGW installer executable (` exe `) file from SourceForge. 20 | 21 | http://sourceforge.net/projects/mingw/files/Automated%20MinGW%20Installer/mingw-get-inst/ 22 | 23 | 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 `. 24 | 25 | 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. 26 | 27 | For Repository Catalogues, check the Download latest repository catalogues button. 28 | 29 | 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. 30 | 31 | For Ready to Install, review and verify the installation settings, which should look similar this: 32 | ``` 33 | Installing: 34 | mingw-get 35 | pkginfo 36 | C Compiler 37 | MSYS Basic System 38 | MinGW Developer Toolkit 39 | Downloading latest repository catalogues 40 | Destination location: 41 | C:\MinGW 42 | ``` 43 | When the installation settings are correct, Install. 44 | 45 | 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. 46 | 47 | The MSYS terminal window may be opened by opening and running the ` C:\MinGW\msys\1.0\msys.bat ` batch file. 48 | 49 | ## Build 50 | 51 | ``` 52 | git clone https://go.googlesource.com/go 53 | cd go\src 54 | all.bat 55 | ``` 56 | 57 | ## 64-bit Notes 58 | 59 | 1. Ensure you are able to compile a working 32-bit Go first. 60 | 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. 61 | 1. Replace ` gcc.exe ` and ` ar.exe ` with their 64-bit counterparts. 62 | 1. Set ` GOARCH=amd64 ` and away you go! 63 | 64 | -------------------------------------------------------------------------------- /docs/Go1point1Gotchas.md: -------------------------------------------------------------------------------- 1 | # Go 1.1 "gotchas" 2 | 3 | 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. 4 | 5 | Here are a few ways in which the bug fixes in Go 1.1 may have broken your Go programs. 6 | 7 | 8 | ## Unknown foo.Bar field in struct literal 9 | 10 | Struct field names must not include package qualifiers. 11 | For example, take this struct with an embedded ` *bytes.Buffer ` field: 12 | 13 | ``` 14 | type S struct { 15 | *bytes.Buffer 16 | } 17 | ``` 18 | 19 | In Go 1.0 the compiler would (incorrectly) accept this struct literal: 20 | 21 | ``` 22 | s := S{ 23 | bytes.Buffer: new(bytes.Buffer), 24 | } 25 | ``` 26 | 27 | Under Go 1.1 the compiler rejects this. 28 | Instead you should use the field name without the package qualifier: 29 | 30 | ``` 31 | s := S{ 32 | Buffer: new(bytes.Buffer), 33 | } 34 | ``` 35 | 36 | ## Initialization loop 37 | 38 | The Go 1.1 compiler now better detects initialization loops. 39 | 40 | For instance, the following code compiled under Go 1.0. 41 | 42 | ``` 43 | var funcVar = fn 44 | 45 | func fn() { 46 | funcVar() 47 | } 48 | ``` 49 | 50 | Such code must now use an ` init ` function for the variable assignment to avoid 51 | the initialization loop. 52 | 53 | ``` 54 | var funcVar func() 55 | 56 | func fn() { 57 | funcVar() 58 | } 59 | 60 | func init() { 61 | funcVar = fn 62 | } 63 | ``` 64 | 65 | In particular, this affects users of App Engine's [delay package](https://developers.google.com/appengine/docs/go/taskqueue/delay). 66 | 67 | 68 | ## Cannot fallthrough final case in switch 69 | 70 | Go 1.0 permitted fallthrough in the final case of a switch statement: 71 | 72 | ``` 73 | switch { 74 | case false: 75 | fallthrough // fall through to 'true' case 76 | case true: 77 | fallthrough // fall through to... nowhere? 78 | } 79 | ``` 80 | 81 | A language change affecting [return requirements](http://golang.org/doc/go1.1#return) led us to make the superfluous fallthrough illegal. 82 | 83 | The fix is to remove such statements from your code. 84 | 85 | 86 | ## Duplicate argument name in parameters and return values 87 | 88 | A compiler bug permitted function type declarations with parameters and return values of the same name. This would compile under Go 1.0: 89 | 90 | ``` 91 | type T func(a int) (a int) 92 | ``` 93 | 94 | Under Go 1.1, the compiler gives an error: 95 | 96 | ``` 97 | duplicate argument a 98 | ``` 99 | 100 | The fix is to rename the arguments so that they use different names. 101 | 102 | 103 | ## Package "go" forbidden 104 | 105 | The import path "go" is now reserved. If you have a package in your workspace 106 | whose import path is "go", you will need to rename it and move it somewhere 107 | else. 108 | 109 | While it was permitted, it is a bad idea to use this import path. 110 | The standard library includes "go/parser", "go/ast", and so on. 111 | It's posssible that a "go" package might be introduced in a future Go release, 112 | making your "go" package unusable. 113 | 114 | Please read [How to write Go code](http://golang.org/doc/code.html) for more 115 | details about import paths. -------------------------------------------------------------------------------- /docs/MinimumRequirements.md: -------------------------------------------------------------------------------- 1 | # 최소 요구사항 2 | 3 | ## 운영체제 (OS) 4 | 5 | ### [Linux](Linux) 6 | 7 | Kernel version 2.6.23 or later. [_This depends on architecture though, we need to have specific builder for this._] Linux/ARMv5 requires much newer kernels, at least v3.1 (for `__kuser_cmpxchg64`). 8 | 9 | We don't support CentOS 5. The kernel is too old (2.6.18). 10 | 11 | For little-endian MIPS64, kernel version [4.1 is known to fail, and 4.8 works](https://golang.org/issue/16848). 12 | 13 | If you are using tinyconfig (e.g. make tinyconfig) for embedded systems, you will also almost certainly enable printk in the kernel as well as a console; we will not include those generic options here. For Go, you must also enable CONFIG_FUTEX. 14 | 15 | ### [Windows](Windows) 16 | 17 | Windows XP (w/ Service Pack 3) or higher. We also test Windows Server 2008 R2, 2012 R2, and 2016, which are roughly Windows 7, Windows 8, and Windows 10. 18 | 19 | ### [macOS (née OS X, aka Darwin)](Darwin) 20 | 21 | macOS Sierra 10.12 or higher requires Go 1.7.1 or above. 22 | Go only supports OS X 10.8 Mountain Lion or newer. We only have builders for 10.10, and 10.11 as of 2018-02-16. 23 | 24 | ### [OpenBSD](OpenBSD) 25 | 26 | The current officially supported -stable versions only. 27 | 28 | ### [DragonFly BSD](DragonFly-BSD) 29 | 30 | Generally only the latest release version only. We have a builder, but it's not the most stable of our ports. 31 | 32 | ### [FreeBSD](FreeBSD) 33 | 34 | FreeBSD 10 or higher, but FreeBSD 12-CURRENT is [not supported](https://github.com/golang/go/issues/22447). 35 | We only run builders testing FreeBSD 10.3 and 11.1. 36 | 37 | ### [NetBSD](NetBSD) 38 | 39 | There are known NetBSD bugs (including kernel crashes) up to the current NetBSD 7.1. There is a reported fix in NetBSD 7.1.1 but it's unverified as of 2017-07-10, as we're not running builders again yet. See https://tip.golang.org/doc/go1.9#known_issues and https://github.com/golang/go/issues/20852 40 | 41 | ### [Native Client](NativeClient) 42 | 43 | pepper_39 or newer. 44 | 45 | ### [Solaris](Solaris) 46 | 47 | illumos (former OpenSolaris 10) based distributions or Oracle Solaris 11+. 48 | 49 | ## Architectures 50 | 51 | ### amd64 52 | 53 | All 64-bit x86 processors. 54 | 55 | ### 386 56 | 57 | See https://golang.org/doc/install/source#environment 58 | 59 | * GO386=387: run on any Pentium MMX or later processor. 60 | * GO386=sse2: run on any processor with at least SSE2 (the default). 61 | 62 | ### arm 63 | 64 | See https://golang.org/doc/install/source#environment 65 | 66 | * GOARM=5: use software floating point; when CPU doesn't have VFP co-processor 67 | * GOARM=6: use VFPv1 only; default if cross compiling; usually ARM11 or better cores (VFPv2 or better is also supported) 68 | * GOARM=7: use VFPv3; usually Cortex-A cores 69 | 70 | ### arm64 71 | 72 | All ARMv8-A processors. 73 | 74 | ### ppc64 (big endian) 75 | 76 | POWER5 and above. 77 | Starting with Go 1.9, only POWER8 and above are supported. 78 | 79 | ### ppc64le (little endian) 80 | 81 | POWER8 and above. 82 | 83 | ### mips64 (big endian) 84 | 85 | MIPS III or higher. Builder is using MIPS64r2. 86 | 87 | ### mips64le (little endian) 88 | 89 | MIPS III or higher in little endian mode. Builders are using Loongson 2E/2F. 90 | 91 | ### s390x 92 | 93 | z196+ 94 | 95 | ### mips (big endian) and mipsle (little endian) 96 | 97 | MIPS32r1, with FPU or kernel FPU emulation -------------------------------------------------------------------------------- /docs/InstallTroubleShooting.md: -------------------------------------------------------------------------------- 1 | (TODO: Add table of contents.) 2 | 3 | # 개요 4 | 5 | 여러분이 Go를 (소스 또는 바이너리 배포판 등에서) 설치하면서, 여러분의 Go는 의도한대로 동작하지 않을 수 있습니다. 이 페이지는 비교적 일반적이거나 진단하기 어려운 문제에 대한 몇 가지 해결 방법들을 수집하고 팁과 솔루션을 제공하는 것을 목적으로 하고 있습니다. 6 | 7 | # 팁 (Tips) 8 | ## 환경 (Environment) 9 | 10 | 시작하려면 먼저 다음을 확인해주세요: 11 | 12 | * GOROOT 13 | * 이것은 **반드시** 여러분이 바이너리 배포판을 사용하고 그것이 기본 위치에 설치되지 않았을때만 설치되어야 합니다. 14 | * [GOPATH](http://golang.org/cmd/go#GOPATH_environment_variable) 15 | * 여러분이 원하는 소스의 디렉토리에 설정해야 합니다. (서드파티(third party) 패키지에서도 적용). 16 | * `:`로 구분된 절대 경로 목록으로 설정할 수도 있습니다. (또는 윈도우즈 에서는 `;`). 17 | * Note that ~/some/path is not absolute and will probably not work the way you expect (try $HOME/some/path instead). 18 | * GOPATH should not be set to or contain GOROOT 19 | * GOBIN 20 | * This should only be set if you _really_ know what you're doing... The default should be fine. 21 | * GOOS, GOARCH, GOHOSTOS, GOHOSTARCH 22 | * You shouldn't need to set these in normal cases. 23 | 24 | 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. 25 | 26 | ## GOROOT vs GOPATH 27 | Packages under GOROOT store their source files in 28 | 29 | ` $GOROOT/src/pkg/import/path/*.go ` 30 | 31 | Notice that this is ` src/pkg `; under GOPATH, source files are stored in 32 | 33 | ` $GOPATH/src/import/path/*.go ` 34 | 35 | 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. 36 | 37 | # 문제 해결하기(Troubleshooting) 38 | #### ` go build ` 명령어가 말을 안들어요! 39 | ` go build ` 명령어는 오직 바이너리 파일을 생성합니다. 만약 여러분이 go build를 패키지 디렉토리에서 실행시켰다면, 패키지를 정상적으로 빌드할 것입니다 (그리고 컴파일에 문제 또한 보여줄 겁니다), 하지만 빌드한 파일을 설치해주지는 않습니다. 정상적인 설치를 원한다면, ` go install ` 명령어를 사용해야 합니다. 만약 여러분이 바이너리 파일 생성을 의도했지만 아무것도 만들어지지 않은 경우, 여러분의 프로젝트가 ` main ` 패키지 안에 있는지 그리고 GOBIN을 세팅하지 않았는지 확인해주세요. 40 | 41 | #### Why does ` go get ` report ` "Fetching https://runtime/cgo?go-get=1" `? 42 | If you have a source distribution, make sure that your packages are up-to-date. Also double check the environment above. 43 | 44 | #### When cross compiling, I get ` "runtime/extern.go:135: undefined: theGoos" ` 45 | Read [[WindowsCrossCompiling]] for some helpful scripts. You can also use the ` --no-clean ` argument when you're building the cross-compile toolchain via ` make.bash `. 46 | 47 | #### Why does ` go get ` work for some packages and report ` permission denied ` in ` $GOROOT ` for some others (with GOPATH set properly)? 48 | 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. 49 | 50 | ## Still need help? 51 | 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: 52 | ``` 53 | go version 54 | go env 55 | env | grep GO 56 | ``` -------------------------------------------------------------------------------- /docs/GerritBot.md: -------------------------------------------------------------------------------- 1 | GerritBot is a tool used for importing GitHub Pull Requests (PRs) into [Gerrit](https://go-review.googlesource.com) for code review. It was created because the Go team does all its reviews in Gerrit, but we'd like to allow a more common workflow for contributing code via GitHub PRs. 2 | 3 | Table of Contents 4 | ================= 5 | 6 | + [Workflow](#workflow) 7 | + [Feedback and Bug Reports](#feedback-and-bug-reports) 8 | + [Frequently Asked Questions](#frequently-asked-questions) 9 | + [I'd like to add a feature/fix a bug](#id-like-to-add-a-featurefix-a-bug) 10 | 11 | ## Workflow 12 | 13 | + A user can upload a PR against any of our GitHub repos just as they would with any other GitHub project that accepts PRs 14 | + The PR changes will then be imported by GerritBot and a message will be posted to the GitHub PR Issue containing a link to the Gerrit review 15 | + All comments are handled within Gerrit. Any comments on the GitHub PR will be ignored 16 | + The PR author can continue to upload commits to the branch used by the PR in order to address feedback from Gerrit 17 | + Once the code is ready to be merged, a maintainer will submit the change on Gerrit and GerritBot will close the issue 18 | + Similarly, if a change is closed or abandoned on Gerrit, the corresponding PR will be closed 19 | 20 | ## Feedback and Bug Reports 21 | 22 | Please [file an issue](https://github.com/golang/go/issues/new?title=x%2Fbuild%2Fcmd%2Fgerritbot%3A%20%3Cfill%20this%20in%3E) and use the `x/build/cmd/gerritbot:` prefix in the title. 23 | 24 | ## Frequently Asked Questions 25 | 26 | ### Why is GerritBot the owner of my change? 27 | 28 | This is due to an [open bug](https://bugs.chromium.org/p/gerrit/issues/detail?id=8296) with the way Gerrit handles acting as another user. Once that is fixed, the original author will also be the owner of the change. 29 | 30 | ### I heard Gerrit requires one commit per change. Can I upload multiple commits to my PR? 31 | 32 | You can upload as many commits as you like. GerritBot will handle squashing your commits into one change that Gerrit can handle. 33 | 34 | ### How does GerritBot determine the final commit message? 35 | 36 | It uses the title and description of the PR to construct the commit message for the Gerrit Change. 37 | 38 | ### I need a Google account to sign up for Gerrit? Why can't I sign in using my GitHub account? 39 | 40 | This is a limitation of the infrastructure that runs our Gerrit instances and is out of our control, plus you already need a Google account to sign our CLA, a requirement for us to accept your contribution in the first place. 41 | 42 | ### I left a reply to a comment in Gerrit but no one but me can see it 43 | 44 | Replies to comments on code in Gerrit are first saved as drafts and need to be published via the “Reply” button. This is to prevent multiple emails per review “session” and is similar to the [pending review workflow](https://help.github.com/articles/reviewing-proposed-changes-in-a-pull-request/) in GitHub. If you see a number next to the “Reply” text in the button, this means you have pending drafts to publish. 45 | 46 | ## I'd like to add a feature/fix a bug 47 | 48 | + If the feature/bug is non-trivial, please [file an issue](https://github.com/golang/go/issues/new?title=x%2Fbuild%2Fcmd%2Fgerritbot%3A%20%3Cfill%20this%20in%3E) first 49 | + The code is located at x/build/cmd/gerritbot 50 | ([GitHub](https://github.com/golang/build/tree/master/cmd/gerritbot), 51 | [Gerrit](https://go.googlesource.com/build/+/master/cmd/gerritbot/)) -------------------------------------------------------------------------------- /docs/PanicAndRecover.md: -------------------------------------------------------------------------------- 1 | Table of Contents 2 | ================= 3 | 4 | + [Panic](#panic) 5 | + [Usage in a Package](#usage-in-a-package) 6 | + [References](#references) 7 | 8 | # Panic 9 | 10 | 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. 11 | 12 | # Usage in a Package 13 | 14 | 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. 15 | 16 | ```go 17 | // A ParseError indicates an error in converting a word into an integer. 18 | type ParseError struct { 19 | Index int // The index into the space-separated list of words. 20 | Word string // The word that generated the parse error. 21 | Error error // The raw error that precipitated this error, if any. 22 | } 23 | 24 | // String returns a human-readable error message. 25 | func (e *ParseError) String() string { 26 | return fmt.Sprintf("pkg: error parsing %q as int", e.Word) 27 | } 28 | 29 | // Parse parses the space-separated words in input as integers. 30 | func Parse(input string) (numbers []int, err error) { 31 | defer func() { 32 | if r := recover(); r != nil { 33 | var ok bool 34 | err, ok = r.(error) 35 | if !ok { 36 | err = fmt.Errorf("pkg: %v", r) 37 | } 38 | } 39 | }() 40 | 41 | fields := strings.Fields(input) 42 | numbers = fields2numbers(fields) 43 | return 44 | } 45 | 46 | func fields2numbers(fields []string) (numbers []int) { 47 | if len(fields) == 0 { 48 | panic("no words to parse") 49 | } 50 | for idx, field := range fields { 51 | num, err := strconv.Atoi(field) 52 | if err != nil { 53 | panic(&ParseError{idx, field, err}) 54 | } 55 | numbers = append(numbers, num) 56 | } 57 | return 58 | } 59 | ``` 60 | 61 | To demonstrate the behavior, consider the following main function: 62 | ```go 63 | func main() { 64 | var examples = []string{ 65 | "1 2 3 4 5", 66 | "100 50 25 12.5 6.25", 67 | "2 + 2 = 4", 68 | "1st class", 69 | "", 70 | } 71 | 72 | for _, ex := range examples { 73 | fmt.Printf("Parsing %q:\n ", ex) 74 | nums, err := Parse(ex) 75 | if err != nil { 76 | fmt.Println(err) 77 | continue 78 | } 79 | fmt.Println(nums) 80 | } 81 | } 82 | ``` 83 | 84 | # References 85 | [Defer, Panic and Recover](https://blog.golang.org/defer-panic-and-recover) 86 | 87 | https://golang.org/ref/spec#Handling_panics 88 | 89 | https://golang.org/ref/spec#Run_time_panics 90 | -------------------------------------------------------------------------------- /docs/LearnConcurrency.md: -------------------------------------------------------------------------------- 1 | This page links to resources for learning about concurrency in Go. The items are presented in order, from beginner material to advanced topics. 2 | 3 | ## Beginner 4 | - Read [Effective Go: Concurrency](https://golang.org/doc/effective_go.html#concurrency) 5 | - Watch [Rob Pike: Concurrency vs. Parallelism](https://vimeo.com/49718712/) 6 | - Study [The Go Programming Language Specification](https://golang.org/ref/spec), especially 7 | - [Go statements](https://golang.org/ref/spec#Go_statements) 8 | - [Channel types](https://golang.org/ref/spec#Channel_types) 9 | - [Send statements](https://golang.org/ref/spec#Send_statements) 10 | - [Receive operator](https://golang.org/ref/spec#Receive_operator) 11 | - [Select statements](https://golang.org/ref/spec#Select_statements) 12 | - Code [A Tour of Go: Concurrency](http://tour.golang.org/concurrency/1) 13 | - Read [Fundamentals of Concurrency](https://www.nada.kth.se/~snilsson/concurrency/) 14 | - Read [Mutexes and Semaphores Demystified](http://www.barrgroup.com/Embedded-Systems/How-To/RTOS-Mutex-Semaphore) 15 | - Read the [Frequently Asked Questions (FAQ)](http://golang.org/doc/faq), especially 16 | - [Why build concurrency on the ideas of CSP?](http://golang.org/doc/faq#csp) 17 | - [Why goroutines instead of threads?](http://golang.org/doc/faq#goroutines) 18 | - [Why are map operations not defined to be atomic?](http://golang.org/doc/faq#atomic_maps) 19 | - [What operations are atomic? What about mutexes?](http://golang.org/doc/faq#What_operations_are_atomic_What_about_mutexes) 20 | - [Why doesn't my multi-goroutine program use multiple CPUs?](http://golang.org/doc/faq#Why_no_multi_CPU) 21 | - [Why does using GOMAXPROCS > 1 sometimes make my program slower?](http://golang.org/doc/faq#Why_GOMAXPROCS) 22 | - [What happens with closures running as goroutines?](http://golang.org/doc/faq#closures_and_goroutines) 23 | - Study [Go by Example](https://gobyexample.com) from [goroutines](https://gobyexample.com/goroutines) through [stateful goroutines](https://gobyexample.com/stateful-goroutines) 24 | 25 | ## Intermediate 26 | - Watch [Go Concurrency Patterns](https://talks.golang.org/2012/concurrency.slide#1) 27 | - Watch [A Practical Guide to Preventing Deadlocks and Leaks in Go](https://www.youtube.com/watch?t=53&v=3EW1hZ8DVyw) 28 | - Read [Share Memory By Communicating](http://blog.golang.org/share-memory-by-communicating) and do the [codewalk](http://golang.org/doc/codewalk/sharemem/) 29 | - Read [Go Concurrency Patterns: Timing out, moving on](http://blog.golang.org/go-concurrency-patterns-timing-out-and) 30 | - Watch [Concurrency is not Parallelism](http://talks.golang.org/2012/waza.slide#1) 31 | - Read [Go Concurrency Patterns: Pipelines and Cancellation](http://blog.golang.org/pipelines) 32 | - Study [Package sync](https://golang.org/pkg/sync/) 33 | - Read [Introducing the Go Race Detector](http://blog.golang.org/race-detector) 34 | - Watch [Go: code that grows with grace](http://talks.golang.org/2012/chat.slide#1) 35 | 36 | ## Advanced 37 | - Read [Advanced Go Concurrency Patterns](http://blog.golang.org/advanced-go-concurrency-patterns) 38 | - Watch [Advanced Go Concurrency Patterns](http://talks.golang.org/2013/advconc.slide#1) 39 | - Read [Go Concurrency Patterns: Context](http://blog.golang.org/context) 40 | - Study [The Go Memory Model](https://golang.org/ref/mem) 41 | - Study [Package atomic](https://golang.org/pkg/sync/atomic/) 42 | - Read [Principles of Designing Go APIs with Channels](https://inconshreveable.com/07-08-2014/principles-of-designing-go-apis-with-channels/) -------------------------------------------------------------------------------- /docs/FileTreeDocumentation.md: -------------------------------------------------------------------------------- 1 | # Go project directory layout 2 | 3 | The Go project itself contains a number of subdirectories. This document will provide a brief overview, but many of these directories have individual README.md or README files that describe their purpose in detail. 4 | 5 | - [api](#api) 6 | - [bin](#bin) 7 | - [blog](#blog) 8 | - [doc](#doc) 9 | - [lib](#lib) 10 | - [misc](#misc) 11 | - [android](#miscandroid) 12 | - [arm](#miscarm) 13 | - [cgo](#misccgo) 14 | - [chrome](#miscchrome) 15 | - [git](#miscgit) 16 | - [ios](#miscios) 17 | - [linkcheck](#misclinkcheck) 18 | - [nacl](#miscnacl) 19 | - [sortac](#miscsortac) 20 | - [swig](#miscswig) 21 | - [tour](#misctour) 22 | - [trace](#misctrace) 23 | - [pkg](#pkg) 24 | - [include](#pkginclude) 25 | - [obj](#pkgobj) 26 | - [tool](#pkgtool) 27 | - [src](#src) 28 | - [test](#test) 29 | 30 | ## api 31 | 32 | The `api` directory contains machine checkable specifications for the Go standard library, to help enforce the [Go 1 compatibility promise](https://golang.org/doc/go1compat). 33 | 34 | ## bin 35 | 36 | The `bin` directory contains the binaries of the project: `go`, `godoc`, and `gofmt`. 37 | 38 | ## blog 39 | 40 | The `blog` directory contains the source and templates for [the Go blog](https://blog.golang.org/). However, the code for serving the blog is at https://godoc.org/golang.org/x/blog 41 | 42 | ## doc 43 | 44 | The `doc` directory contains the resources served at https://golang.org/doc/ 45 | 46 | ## lib 47 | 48 | The `lib` directory contains a single subdirectory `lib/time` which contains a copy of the time zone database that Go uses if it cannot find the operating systems copy. 49 | 50 | ## misc 51 | 52 | ### misc/android 53 | 54 | ### misc/arm 55 | 56 | ### misc/cgo 57 | 58 | The `misc/cgo` directory contains tests and examples of cgo. 59 | 60 | ### misc/chrome 61 | 62 | The `misc/chrome` directory contains a Chrome extension for Go contributors. 63 | 64 | ### misc/git 65 | 66 | The `misc/git` directory contains a pre-commit hook to ensure that go files have been run through gofmt. 67 | 68 | ### misc/ios 69 | 70 | ### misc/linkcheck 71 | 72 | The `misc/linkcheck` directory contains a program for ensuring there are no missing links in the godoc website. 73 | 74 | ### misc/nacl 75 | 76 | The `misc/nacl` directory contains Go's integration with nacl, which is used by [the Go playground](https://play.golang.org). 77 | 78 | ### misc/sortac 79 | 80 | The `misc/sortac` directory contains a utility for sorting the `AUTHORS` and `CONTRIBUTORS` files. 81 | 82 | ### misc/swig 83 | 84 | The `misc/swig` directory contains examples of using Go with [SWIG](https://github.com/swig/swig). 85 | 86 | ### misc/tour 87 | 88 | The `misc/tour` directory contains the resources and source code for the [Go tour](https://tour.golang.org). 89 | 90 | ### misc/trace 91 | 92 | The `misc/trace` directory contains a generated file used by `go tool trace`. 93 | 94 | ## pkg 95 | 96 | The `pkg` directory contains platform-specific build artifacts. It will always contain the following: 97 | 98 | ### pkg/include 99 | 100 | ### pkg/obj 101 | 102 | ### pkg/tool 103 | 104 | The `pkg/tool` directory contains the platform-specific tool chain exposed by the `go tool` command. 105 | 106 | ## src 107 | 108 | The `src` directory contains the source code for the standard library and, in `src/cmd`, tool chain. 109 | 110 | ## test 111 | 112 | The `test` directory contains extensive additional tests for the runtime and tool chain. -------------------------------------------------------------------------------- /docs/CodeReview.md: -------------------------------------------------------------------------------- 1 | Be sure to familiarize yourself with the [code review process](http://golang.org/doc/contribute.html#Code_review) from the official Contribution Guidelines first. 2 | 3 | # Reviewer Parlance 4 | 5 | There are several terms code reviews may use that you should become familiar with. 6 | 7 | * ` LGTM ` — looks good to me 8 | * ` SGTM ` — sounds good to me 9 | * ` PTAL ` — please take a look 10 | * ` s/foo/bar/ ` — please replace ` foo ` with ` bar `; this is [sed syntax](http://en.wikipedia.org/wiki/Sed#Usage) 11 | * ` s/foo/bar/g ` — please replace ` foo ` with ` bar ` throughout your entire change 12 | 13 | # CL Directives 14 | 15 | * `R=foo` — assign a reviewer within the [Go CL dashboard](https://swtch.com/godash/) 16 | * `RELNOTE=yes` or `RELNOTE=` — tag for release notes; scraped by the [relnote](https://golang.org/x/build/cmd/relnote) tool 17 | * `DO NOT SUBMIT` (in the commit message) — block submission; see the "Work in progress" section below 18 | * `Updates #1234` or `Fixes #1234` (in the commit message) — link the CL from the GitHub issue and optionally close the issue after the CL is merged 19 | 20 | # Email 21 | 22 | Messages from a code review are typically sent to three places: 23 | 24 | * the reviewers, if any 25 | * the golang-codereviews group 26 | * the owner 27 | 28 | Please do NOT reply code review via email, as the message [will not be relayed to Gerrit](https://code.google.com/p/gerrit/issues/detail?id=228). Always click on the link and post reply in Gerrit. 29 | 30 | # Work in progress 31 | 32 | If you have changes that aren't ready to be reviewed, you can put a giant **`DO NOT REVIEW`** as the second line of the CL description, so that people who see it know not to look any further. Don't make it the first line, since then it will become the subject for the entire review, even after you've changed the description. 33 | 34 | Similarly, if you would like to ensure that your changes are not merged by mistake, you can put **`DO NOT SUBMIT`** as the second line of the CL description. 35 | 36 | If you don't need Gerrit's features, but just want to backup your work, share work between multiple clients, or have a staging UI to examine your changes, you can use a regular git remote. 37 | 38 | To use GitHub as a git remote, you can either fork github.com/golang/go or create a new repo. There are trade-offs. Forked repos will have a faster first push. Non-forked repos can be private. Forked repos are associated in GitHub's system. As a result, they are easily discoverable and support cross-repo comparisons in the GitHub UI; however, this also means that references to issues in commit messages in forked repos will create references to your fork in the issue. 39 | 40 | To add your git remote, run something like: 41 | 42 | ```bash 43 | $ git remote add fork git@github.com:yourusername/go.git 44 | ``` 45 | 46 | You can then push changes to the "fork" remote with `git push fork branchname`. 47 | 48 | Gerrit's code review model is to rewrite a single commit until it is correct. GitHub will try to prevent you from accidentally overwriting your existing branch. You can work around this by forcing the push: `git push --force fork branchname`. Alternatively, you can set up your forked remote as a mirror by cloning it initially with: 49 | 50 | ```bash 51 | $ git remote add --mirror=push fork git@github.com:yourusername/go.git 52 | ``` 53 | 54 | Then running `git push fork` will update GitHub to perfectly mirror *everything* (all branches, all tags, etc.). This is handy, but take care when using this on multiple clients. You are bypassing the usual git safeguards, so it is easy to overwrite (and thus lose) work pushed by a different client. -------------------------------------------------------------------------------- /docs/SQLInterface.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | 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. 4 | 5 | This page provides example usage patterns. 6 | 7 | # Database driver 8 | 9 | The database/sql package must be used in conjunction with a database driver. 10 | See http://golang.org/s/sqldrivers for a list of drivers. 11 | 12 | The documentation below assumes a driver has been imported. 13 | 14 | # Connecting to a database 15 | 16 | Open is used to create a database handle: 17 | 18 | ```go 19 | db, err := sql.Open(driver, dataSourceName) 20 | ``` 21 | 22 | Where driver specifies a database driver and dataSourceName 23 | specifies database-specific connection information 24 | such as database name and authentication credentials. 25 | 26 | 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: 27 | 28 | ```go 29 | if err := db.Ping(); err != nil { 30 | log.Fatal(err) 31 | } 32 | ``` 33 | 34 | After use, the database is closed using Close. 35 | 36 | # Executing queries 37 | 38 | Exec is used for queries where no rows are returned: 39 | 40 | ```go 41 | result, err := db.Exec( 42 | "INSERT INTO users (name, age) VALUES ($1, $2)", 43 | "gopher", 44 | 27, 45 | ) 46 | ``` 47 | 48 | Where result contains the last insert ID and number of 49 | rows affected. The availability of these values is dependent on 50 | the database driver. 51 | 52 | Query is used for retrieval: 53 | 54 | ```go 55 | rows, err := db.Query("SELECT name FROM users WHERE age = $1", age) 56 | if err != nil { 57 | log.Fatal(err) 58 | } 59 | for rows.Next() { 60 | var name string 61 | if err := rows.Scan(&name); err != nil { 62 | log.Fatal(err) 63 | } 64 | fmt.Printf("%s is %d\n", name, age) 65 | } 66 | if err := rows.Err(); err != nil { 67 | log.Fatal(err) 68 | } 69 | ``` 70 | 71 | QueryRow is used where only a single row is expected: 72 | 73 | ```go 74 | var age int64 75 | row := db.QueryRow("SELECT age FROM users WHERE name = $1", name) 76 | err := row.Scan(&age) 77 | ``` 78 | 79 | Prepared statements can be created with Prepare: 80 | 81 | ```go 82 | age := 27 83 | stmt, err := db.Prepare("SELECT name FROM users WHERE age = $1") 84 | if err != nil { 85 | log.Fatal(err) 86 | } 87 | rows, err := stmt.Query(age) 88 | // process rows 89 | ``` 90 | 91 | Exec, Query and QueryRow can be called on statements. After use, a 92 | statement should be closed with Close. 93 | 94 | # Transactions 95 | 96 | Transactions are started with Begin: 97 | 98 | ```go 99 | tx, err := db.Begin() 100 | if err != nil { 101 | log.Fatal(err) 102 | } 103 | ``` 104 | 105 | The Exec, Query, QueryRow and Prepare functions already covered can be 106 | used in a transaction. 107 | 108 | A transaction must end with a call to Commit or Rollback. 109 | 110 | # Dealing with NULL 111 | 112 | If a database column is nullable, one of the types supporting null values should be passed to Scan. 113 | 114 | For example, if the name column in the names table is nullable: 115 | 116 | ```go 117 | var name NullString 118 | err := db.QueryRow("SELECT name FROM names WHERE id = $1", id).Scan(&name) 119 | ... 120 | if name.Valid { 121 | // use name.String 122 | } else { 123 | // value is NULL 124 | } 125 | ``` 126 | 127 | Only NullBool, NullFloat64, NullInt64 and NullString are implemented in 128 | database/sql. Implementations of database-specific null types are left 129 | to the database driver. -------------------------------------------------------------------------------- /docs/NewSpeakers.md: -------------------------------------------------------------------------------- 1 | # Resources for New Speakers 2 | 3 | Go needs everyone's help. 4 | We want to see more new speakers with new perspectives at Go conferences, 5 | especially more women and others underrepresented in the Go community. 6 | 7 | The process of applying to speak at a tech conference can be a bit opaque and confusing 8 | for first-time speakers. 9 | In general, please remember that, first and foremost, 10 | conferences organizers want to find great talks; 11 | there is no single format or recipe for a great talk; 12 | and you need not be a Go expert to give a great talk. 13 | All that you need to be is excited about sharing something 14 | you've observed or learned about using Go. 15 | 16 | Here are some good blog posts with tips for writing conference talk proposals: 17 | 18 | - “[How to write a successful conference proposal](https://dave.cheney.net/2017/02/12/how-to-write-a-successful-conference-proposal)” by Dave Cheney 19 | - “[How to write a successful conference proposal](https://medium.com/@fox/how-to-write-a-successful-conference-proposal-4461509d3e32)” by Karolina Szczur 20 | - “[Is your conference proposal good enough?](http://rckbt.me/2014/01/conference-proposals/)” by Raquel Vélez (rockbot) 21 | - “[What your conference proposal is missing](http://www.sarahmei.com/blog/2014/04/07/what-your-conference-proposal-is-missing/)” by Sarah Mei 22 | 23 | Elsewhere on the wiki, we maintain a list of [upcoming conferences](Conferences) with links to CFPs. 24 | The same page also lists past conferences with links to talk videos. 25 | 26 | Right now, these conferences are looking for new speakers: 27 | 28 | - [GopherCon Singapore](https://www.papercall.io/gopherconsg-2018), May 4, 2018. Proposals due February 28. 29 | - [GopherCon Iceland](https://www.papercall.io/gophercon-iceland), June 1-2, 2018. Proposals due March 3. 30 | - [GopherCon, Denver](https://www.papercall.io/gophercon2018), August 28-29, 2018. Proposals due March 15. 31 | - [GoLab, Italy](https://www.papercall.io/golab2018), October 22-23, 2018. Proposals due April 4. 32 | 33 | They welcome speakers of all experience levels and backgrounds! 34 | 35 | ## Contact Us 36 | 37 | We, the Go community members listed below, 38 | are happy to discuss or review talk proposals 39 | and answer other questions about the overall speaking process. 40 | Feel free to contact any of us directly. 41 | 42 | - Russ Cox, rsc@golang.org, [@_rsc](https://twitter.com/_rsc) 43 | - Steve Francia, spf@golang.org, [@spf13](https://twitter.com/spf13) 44 | - William Kennedy, bill@ardanlabs.com, [@goinggodotnet](https://twitter.com/goinggodotnet) 45 | - Cassandra Salisbury, cassandra@golangbridge.org, [@cassandraoid](https://twitter.com/cassandraoid) 46 | - Ashley McNamara, ashmc@microsoft.com, [@ashleymcnamara](https://twitter.com/ashleymcnamara) 47 | - Brian Ketelsen, bjk@microsoft.com, [@bketelsen](https://twitter.com/bketelsen) 48 | - Natalie Pistunovich natalie@golangbridge.org, [@nataliepis](https://twitter.com/nataliepis) 49 | - Erik St. Martin, erikstm@microsoft.com, [@erikstmartin](https://twitter.com/erikstmartin) 50 | - Francesc Campoy, campoy@golang.org, [@francesc](https://twitter.com/francesc) 51 | - Sameer Ajmani, sameer@google.com, [@Sajma](https://twitter.com/Sajma) 52 | - Florin Pățan, florinpatan@gmail.com, [@dlsniper](https://twitter.com/dlsniper) 53 | - Aaron Schlesinger, arschles@gmail.com, [@arschles](https://twitter.com/arschles) 54 | - Paul Jolly, paul@myitcv.io [@_myitcv](https://twitter.com/_myitcv) 55 | - Alexey Palazhchenko, alexey.palazhchenko@gmail.com [@paaleksey](https://twitter.com/paaleksey) (English, Russian) 56 | 57 | (Experienced speakers, feel free to add your contact information to the list, or email rsc@golang.org if you don't have wiki edit permission.) -------------------------------------------------------------------------------- /docs/HandlingIssues.md: -------------------------------------------------------------------------------- 1 | This document explains how we handle issue triage and scheduling in [the Go project's issue tracker](http://golang.org/issue). 2 | 3 | # Issue States 4 | 5 | Any issue must be in one of the following five states. Project contributors move issues from one state to another by doing things. The intent behind these explicit states is to describe the (minimum) next steps required to bring the issue to resolution. Issues may move between states in any order, as dictated by the needs of the particular issue. 6 | 7 | New 8 | - The issue has been filed. 9 | - May not be correctly formatted (title, etc). 10 | - To transition from this state, someone must clean up the issue report and optionally cc people who might best investigate or fix it. 11 | 12 | Needs Investigation 13 | - Is correctly formatted (the title has a path prefix, and the body describes the issue). 14 | - Has the label `NeedsInvestigation`. 15 | - May have the label `WaitingForInfo` if the investigator is waiting for more information from someone (e.g., the issue reporter). 16 | - To transition from this state, someone must examine it and confirm that it is a valid issue and not a duplicate of an existing issue. 17 | 18 | Needs Decision 19 | - The issue is real, but we're not sure what action to take. Feedback is required from experts, contributors, and/or the community before a fix can be made. 20 | - Note that the majority of issues will never transition to this state, as most of the time the decision is an obvious "Yes, this should be fixed." 21 | - Has the label `NeedsDecision`. 22 | - Has a milestone. 23 | - May have the label `Blocked` if forward progress cannot be made pending the resolution of another issue or the release of a future version of Go (an accompanying comment should explain the blockage). 24 | - May have the label `WaitingForInfo`. 25 | - To transition from this state, someone must decide how the issue is to be resolved. 26 | - If the decision is complicated, the issue may be given a `Proposal` label and the issue remains in this state until the proposal process is complete. 27 | 28 | Needs Fix 29 | - The path to resolution is known, but the work has not been done. 30 | - Has the label `NeedsFix`. 31 | - Has a milestone. 32 | - May have the labels `Blocked` or `WaitingForInfo`. 33 | - To transition from this state, someone must do the work to fix the issue. 34 | 35 | Fixed 36 | - The issue is resolved. No further attention is required. 37 | - Is closed. 38 | 39 | Issues move from one state to another where appropriate. For example, a contributor may file an issue, assign it to themselves, and immediately apply the `NeedsFix` label. Or, an issue may go from `NeedsDecision` to `NeedsFix`, only to later move back to `NeedsDecision` as complexities arise. 40 | 41 | An issue may be closed at any time, with a comment to indicate the reason for closure ("fixed by …", "duplicate of …", "working as intended", etc). 42 | 43 | At any state (except New) the issue may be assigned to someone. 44 | Unassigned issues are considered available for anyone to address. 45 | 46 | # Milestones 47 | Milestones describe the timeline for issue resolution. 48 | 49 | - Go1.x.y 50 | 51 | Must be fixed for release 1.x.y, or explicitly postponed to a later release. 52 | 53 | - Proposal 54 | 55 | Is a proposal and does not pertain to a specific release. 56 | 57 | - Soon 58 | 59 | Should be fixed soon, but is not included in or needed by a release. 60 | 61 | - Unplanned 62 | 63 | Might be fixed at some point, but nobody is planning to do it. 64 | 65 | - Unreleased 66 | 67 | Is not included in or needed by a release. 68 | 69 | - Gccgo 70 | 71 | For gccgo issues. 72 | 73 | - Go2 74 | 75 | Deferred until Go 2. 76 | 77 | Additional milestones may be used to manage specific project work. -------------------------------------------------------------------------------- /docs/DevExp.md: -------------------------------------------------------------------------------- 1 | # Developer Experience Working Group (draft) 2 | 3 | Developer Experience Working Group is a team trying to make the Go programming language, libraries and tools more pleasant to use. The team primarily works on the Go project, even though its responsibilities and activities may involve contributing to the ecosystem-wide impactful projects. The group is aimed to cover a highly specialized field of expertise that is not always well-covered by the core team. 4 | 5 | ## Goals 6 | 7 | * Making Go a preferred language in industry and education. 8 | * Helping the language graduate to a mainstream language by enabling the early majority developers. 9 | * Helping Go to succeed in organizations with opinionated infrastructure and tooling. 10 | 11 | ## Projects 12 | Ongoing projects, feel free to reach out to the project lead if you want to collaborate: 13 | 14 | - Improvements to the Go installation experience (Chris Broadfoot ) 15 | - Guides on tooling and developer environments (editors and IDEs) (Jaana B. Dogan ) 16 | - Running user studies to systematically analyze and measure friction points (Chris Broadfoot , Katrina Owen , Steve Francia ) 17 | - Improvements to the Go Tour and Go Playground (Chris Broadfoot , Steve Francia ) 18 | - Better guidelines to help new users and visual aids for golang.org (Jaana B. Dogan ) 19 | 20 | ## Channels 21 | * Mailing list: [golang-devexp](https://groups.google.com/forum/#!forum/golang-devexp) 22 | * Gophers Slack channel if you need synchronous help: [#devexp](https://gophers.slack.com/archives/devexp) ([invitation](https://invite.slack.golangbridge.org/)) 23 | 24 | ## Responsibilities and Activities 25 | * Identify the barriers for newcomers and remove them to make Go succeed as a mainstream programming language. 26 | Revamp the existing docs and tools. 27 | * Systematically collect feedback from the Go users to improve friction points in standard library, tools, docs, language and the ecosystem. The group may also run UX studies. 28 | * Help identifying the critical missing libraries/tools from the ecosystem. 29 | * At each release cycle, review new standard library APIs to give feedback about usability, self-explanation and documentation. 30 | * Participate in user-facing Go proposals to give usability feedback. 31 | * Encourage readable and idiomatic APIs. Be the voice of best practices in API design. 32 | * Contribute with technical writing on the Go blog to fill the gaps in communication. 33 | 34 | ## Roles 35 | 36 | The group has a variety of roles with specific responsibilities. Although it is not a hard requirement, all contributors are expected to have background and technical expertise in one or more of these fields: API design, developer tooling, readability, programming language design and education, and technical writing. 37 | 38 | ### Leads 39 | We are expecting this role to require 15 hours of commitment each week. 40 | * All responsibilities of the members 41 | * Ensuring contributors are sufficiently productive and not blocked 42 | * Reaching consensus if there is no obvious answer 43 | * Organizing meetings and handling paperwork 44 | 45 | ### Members 46 | We are expecting this role to require 10 hours of commitment each week. 47 | * All responsibilities of the participants 48 | * Doing the first CL and proposal reviews 49 | * Setting high-level goals and establishing long-term milestones 50 | * Mentor community about best practices 51 | 52 | ### Participants 53 | Participants don't have to commit to any long-term plans, they work as much as they want on gradual improvements and contribute to the discussion. 54 | * Creating CLs and proposals 55 | * Participating in discussions 56 | -------------------------------------------------------------------------------- /docs/SliceTricks.md: -------------------------------------------------------------------------------- 1 | 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 `. 2 | 3 | Here are the vector methods and their slice-manipulation analogues: 4 | 5 | #### AppendVector 6 | ```go 7 | a = append(a, b...) 8 | ``` 9 | 10 | #### Copy 11 | ```go 12 | b = make([]T, len(a)) 13 | copy(b, a) 14 | // or 15 | b = append([]T(nil), a...) 16 | ``` 17 | 18 | #### Cut 19 | ```go 20 | a = append(a[:i], a[j:]...) 21 | ``` 22 | 23 | #### Delete 24 | ```go 25 | a = append(a[:i], a[i+1:]...) 26 | // or 27 | a = a[:i+copy(a[i:], a[i+1:])] 28 | ``` 29 | 30 | #### Delete without preserving order 31 | ```go 32 | a[i] = a[len(a)-1] 33 | a = a[:len(a)-1] 34 | 35 | ``` 36 | **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: 37 | > **Cut** 38 | ```go 39 | copy(a[i:], a[j:]) 40 | for k, n := len(a)-j+i, len(a); k < n; k++ { 41 | a[k] = nil // or the zero value of T 42 | } 43 | a = a[:len(a)-j+i] 44 | ``` 45 | 46 | > **Delete** 47 | ```go 48 | copy(a[i:], a[i+1:]) 49 | a[len(a)-1] = nil // or the zero value of T 50 | a = a[:len(a)-1] 51 | ``` 52 | 53 | > **Delete without preserving order** 54 | ```go 55 | a[i] = a[len(a)-1] 56 | a[len(a)-1] = nil 57 | a = a[:len(a)-1] 58 | ``` 59 | 60 | #### Expand 61 | ```go 62 | a = append(a[:i], append(make([]T, j), a[i:]...)...) 63 | ``` 64 | 65 | #### Extend 66 | ```go 67 | a = append(a, make([]T, j)...) 68 | ``` 69 | 70 | #### Insert 71 | ```go 72 | a = append(a[:i], append([]T{x}, a[i:]...)...) 73 | ``` 74 | **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: 75 | > **Insert** 76 | ```go 77 | s = append(s, 0) 78 | copy(s[i+1:], s[i:]) 79 | s[i] = x 80 | ``` 81 | 82 | #### InsertVector 83 | ```go 84 | a = append(a[:i], append(b, a[i:]...)...) 85 | ``` 86 | 87 | #### Pop/Shift 88 | ```go 89 | x, a = a[0], a[1:] 90 | ``` 91 | 92 | #### Pop Back 93 | ```go 94 | x, a = a[len(a)-1], a[:len(a)-1] 95 | ``` 96 | 97 | #### Push 98 | ```go 99 | a = append(a, x) 100 | ``` 101 | 102 | #### Push Front/Unshift 103 | ```go 104 | a = append([]T{x}, a...) 105 | ``` 106 | 107 | ## Additional Tricks 108 | ### Filtering without allocating 109 | 110 | 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. 111 | 112 | ```go 113 | b := a[:0] 114 | for _, x := range a { 115 | if f(x) { 116 | b = append(b, x) 117 | } 118 | } 119 | ``` 120 | 121 | ### Reversing 122 | 123 | To replace the contents of a slice with the same elements but in reverse order: 124 | ```go 125 | for i := len(a)/2-1; i >= 0; i-- { 126 | opp := len(a)-1-i 127 | a[i], a[opp] = a[opp], a[i] 128 | } 129 | ``` 130 | The same thing, except with two indices: 131 | ```go 132 | for left, right := 0, len(a)-1; left < right; left, right = left+1, right-1 { 133 | a[left], a[right] = a[right], a[left] 134 | } 135 | ``` 136 | 137 | ### Shuffling 138 | 139 | Fisher–Yates algorithm: 140 | ```go 141 | for i := len(a) - 1; i > 0; i-- { 142 | j := rand.Intn(i + 1) 143 | a[i], a[j] = a[j], a[i] 144 | } 145 | ``` -------------------------------------------------------------------------------- /docs/Gardening.md: -------------------------------------------------------------------------------- 1 | # Gardening 2 | 3 | ## What is gardening? 4 | 5 | "Gardening" in open source projects refers to the background maintenance tasks done to keep the project healthy & growing & nice looking. 6 | 7 | This page lists common Go gardening tasks. 8 | 9 | ## Access 10 | 11 | If you've been regularly active in the Go community for some time, feel free to ask for Gerrit and/or Github access to modify things. 12 | 13 | See http://golang.org/wiki/GerritAccess and http://golang.org/wiki/GithubAccess 14 | 15 | ## Gardening Tasks 16 | 17 | Before doing any gardening work, especially on the issue tracker, remember to familiarize yourself with the issues life-cycle, described here: [Handling Issues - Issue States](https://github.com/golang/go/wiki/HandlingIssues#issue-states). 18 | 19 | ### Fix red 20 | 21 | Look at https://build.golang.org/ --- is anything red? Fix or file bugs or nag people. The build dashboard should never be red, even occasionally. If the tree is red, people can't work effectively because TryBots and such will just report failures, masking other problems. 22 | 23 | ### Triage new bugs 24 | 25 | Look at the untriaged bugs. For Go, we use the presence of a Milestone field and at least one label to mean that the bug has been triaged. To search for un-milestoned, un-labeled issues, use https://github.com/golang/go/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+no%3Amilestone+no%3Alabel 26 | 27 | While triaging the bug: 28 | 29 | * is it a duplicate? Close it, referencing the dup. 30 | * is it a Question rather than a bug? Close it and reply with something like "For questions about Go, see https://golang.org/wiki/Questions" 31 | * is the subject the correct format? It should start with the package path and a colon: "net/http: fix crash in Server during foo operation" 32 | * is it in a subrepo? Set the milestone to "Unreleased". Unless it's a subrepo that goes into a release, like godoc or http2. 33 | * if it is a regression and you can reproduce it, use git bisect to find the bad commit (optional but very helpful). 34 | 35 | See https://golang.org/wiki/HandlingIssues for how we use Github's issue metadata. 36 | 37 | ### WaitingForInfo 38 | 39 | Find bugs that are in state WaitingForInfo (https://github.com/golang/go/labels/WaitingForInfo) and ping them, remove the label when replies arrive, or close the bugs if a reply never arrived. 40 | 41 | ### "Unplanned" bugs 42 | 43 | "Unplanned" issues have a habit of being neglected. Check out old ones and see if they're easily fixable (and can be moved to a Go1.n or Go 1.nMaybe milestone), or should be closed. 44 | 45 | These are the Unplanned bugs sorted by age, most stale ones first: https://github.com/golang/go/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aopen%20milestone%3AUnplanned%20sort%3Aupdated-asc%20-label%3AGo2%20-label%3ALanguageChange 46 | 47 | ### Pending CLs 48 | 49 | Review the format of commit messages and presence of tests and formatting of code and typos/grammar in incoming pending CLs. All of that can be done without determining the correctness of the change itself. See https://dev.golang.org/release for the list of pending CLs. 50 | 51 | Once it has a +1, the owner of that area can give it a +2. 52 | 53 | Read a +1 as meaning "triaged", or "not obviously wrong". If it has tests, is formatted properly (references a bug number, probably), and is ready for more review, give it a +1. 54 | 55 | ### Pending CLs: ask about tests 56 | 57 | If a new CL arrives without a test, but could/should have a test, ask if they could add a test. Or suggest how. 58 | 59 | ### Pending CLs: run TryBots 60 | 61 | If you have access (see https://golang.org/wiki/GerritAccess) to run the TryBots and you see a CL with plausible (and non-malicious) code, kick off the TryBots. (We've never seen malicious code trying to escape our TryBot sandboxes, but that's why it's not automatic yet. Please alert us if you see something.) 62 | -------------------------------------------------------------------------------- /docs/PortingPolicy.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | 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. 4 | 5 | The goal of this policy is to avoid the accumulation of incomplete or broken ports. 6 | 7 | # Requirements for a new port 8 | 9 | Before any code relating to a port can be added to the main Go repository, the following must all be done: 10 | 11 | * 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. 12 | 13 | * A developer must be named (and agree) to maintain the builder, the machine trying each git revision and providing data for http://build.golang.org. 14 | 15 | * The builder must already be running (and failing, because the code is not yet in the main repository). 16 | 17 | * 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. 18 | 19 | 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. 20 | 21 | 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. 22 | 23 | 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. 24 | 25 | # Other repositories 26 | 27 | Although it is not part of the core repository, the x/sys repository should add support for the new port before the release happens because it is the official place to add new system calls. 28 | 29 | # First class ports 30 | 31 | Some ports are considered "first class". The distinction is mostly about releases and distribution. 32 | 33 | A first class port has these properties: 34 | 35 | * Broken builds block releases 36 | * All contributors are effectively responsible for these ports (You break it, you fix it, or find someone who can.) 37 | * Official binaries are provided 38 | * Requires Google's Go team to own the builder machine 39 | * Installation is documented at http://golang.org/doc/install 40 | 41 | Graduating a port to "first class" is at the discretion of the Go team at Google. 42 | 43 | The current first class ports are: 44 | 45 | * linux/amd64 46 | * linux/386 47 | * linux/arm 48 | * darwin/amd64 49 | * windows/amd64 50 | * windows/386 51 | 52 | We distribute binaries for other GOOS/GOARCH pairs (other "ports"), but they are not "first class" by this definition. 53 | 54 | # Removing a port 55 | 56 | 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. 57 | 58 | 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. 59 | 60 | If a builder fails for more than two weeks, it is time to start looking for a more active maintainer for the port. 61 | 62 | 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. 63 | 64 | Due to backwards compatibility concerns, removing a formerly working port should be a last resort. Finding a new maintainer is always preferable. 65 | 66 | # Comments and Questions 67 | 68 | Comments or questions about the policy should be sent to golang-dev. -------------------------------------------------------------------------------- /docs/WindowsDLLs.md: -------------------------------------------------------------------------------- 1 | # Calling a Windows DLL 2 | 3 | There are a few ways to call "C" code from inside Go 4 | 5 | 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). 6 | 7 | A sample program that calls Windows DLLs from Go: 8 | 9 | ```go 10 | package main 11 | 12 | import ( 13 | "fmt" 14 | "syscall" 15 | "unsafe" 16 | ) 17 | 18 | func abort(funcname string, err error) { 19 | panic(fmt.Sprintf("%s failed: %v", funcname, err)) 20 | } 21 | 22 | var ( 23 | kernel32, _ = syscall.LoadLibrary("kernel32.dll") 24 | getModuleHandle, _ = syscall.GetProcAddress(kernel32, "GetModuleHandleW") 25 | 26 | user32, _ = syscall.LoadLibrary("user32.dll") 27 | messageBox, _ = syscall.GetProcAddress(user32, "MessageBoxW") 28 | ) 29 | 30 | const ( 31 | MB_OK = 0x00000000 32 | MB_OKCANCEL = 0x00000001 33 | MB_ABORTRETRYIGNORE = 0x00000002 34 | MB_YESNOCANCEL = 0x00000003 35 | MB_YESNO = 0x00000004 36 | MB_RETRYCANCEL = 0x00000005 37 | MB_CANCELTRYCONTINUE = 0x00000006 38 | MB_ICONHAND = 0x00000010 39 | MB_ICONQUESTION = 0x00000020 40 | MB_ICONEXCLAMATION = 0x00000030 41 | MB_ICONASTERISK = 0x00000040 42 | MB_USERICON = 0x00000080 43 | MB_ICONWARNING = MB_ICONEXCLAMATION 44 | MB_ICONERROR = MB_ICONHAND 45 | MB_ICONINFORMATION = MB_ICONASTERISK 46 | MB_ICONSTOP = MB_ICONHAND 47 | 48 | MB_DEFBUTTON1 = 0x00000000 49 | MB_DEFBUTTON2 = 0x00000100 50 | MB_DEFBUTTON3 = 0x00000200 51 | MB_DEFBUTTON4 = 0x00000300 52 | ) 53 | 54 | func MessageBox(caption, text string, style uintptr) (result int) { 55 | var nargs uintptr = 4 56 | ret, _, callErr := syscall.Syscall9(uintptr(messageBox), 57 | nargs, 58 | 0, 59 | uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(text))), 60 | uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(caption))), 61 | style, 62 | 0, 63 | 0, 64 | 0, 65 | 0, 66 | 0) 67 | if callErr != 0 { 68 | abort("Call MessageBox", callErr) 69 | } 70 | result = int(ret) 71 | return 72 | } 73 | 74 | func GetModuleHandle() (handle uintptr) { 75 | var nargs uintptr = 0 76 | if ret, _, callErr := syscall.Syscall(uintptr(getModuleHandle), nargs, 0, 0, 0); callErr != 0 { 77 | abort("Call GetModuleHandle", callErr) 78 | } else { 79 | handle = ret 80 | } 81 | return 82 | } 83 | 84 | func main() { 85 | defer syscall.FreeLibrary(kernel32) 86 | defer syscall.FreeLibrary(user32) 87 | 88 | fmt.Printf("Return: %d\n", MessageBox("Done Title", "This test is Done.", MB_YESNOCANCEL)) 89 | } 90 | 91 | func init() { 92 | fmt.Print("Starting Up\n") 93 | } 94 | ``` 95 | 96 | 97 | 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 98 | 99 | ```go 100 | package main 101 | 102 | import ( 103 | "fmt" 104 | "syscall" 105 | "unsafe" 106 | ) 107 | 108 | func main() { 109 | var mod = syscall.NewLazyDLL("user32.dll") 110 | var proc = mod.NewProc("MessageBoxW") 111 | var MB_YESNOCANCEL = 0x00000003 112 | 113 | ret, _, _ := proc.Call(0, 114 | uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("This test is Done."))), 115 | uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("Done Title"))), 116 | uintptr(MB_YESNOCANCEL)) 117 | fmt.Printf("Return: %d\n", ret) 118 | 119 | } 120 | ``` 121 | 122 | A third way would be to call into libraries basically by "linking" against the library, using the "[[cgo]]" method (this way works in Linux and Windows): 123 | 124 | This way would look something like this 125 | 126 | ```go 127 | import ("C") 128 | ... 129 | C.MessageBoxW(...) 130 | ``` 131 | 132 | See [[cgo]] for further details. -------------------------------------------------------------------------------- /docs/Gomote.md: -------------------------------------------------------------------------------- 1 | # Using gomote 2 | 3 | ## Installing 4 | 5 | ``` 6 | $ go get -u golang.org/x/build/cmd/gomote 7 | ``` 8 | 9 | ## Using 10 | 11 | TODO: examples. For now: 12 | 13 | ``` 14 | The gomote command is a client for the Go builder infrastructure. 15 | It's a remote control for remote Go builder machines. 16 | 17 | Usage: 18 | 19 | gomote [global-flags] cmd [cmd-flags] 20 | 21 | For example, 22 | $ gomote create openbsd-amd64-60 23 | user-username-openbsd-amd64-60-0 24 | $ gomote push user-username-openbsd-amd64-60-0 25 | $ gomote run user-username-openbsd-amd64-60-0 go/src/make.bash 26 | $ gomote run user-username-openbsd-amd64-60-0 go/bin/go test -v -short os 27 | 28 | To list the subcommands, run "gomote" without arguments: 29 | 30 | Commands: 31 | 32 | create create a buildlet 33 | destroy destroy a buildlet 34 | gettar extract a tar.gz from a buildlet 35 | list list buildlets 36 | ls list the contents of a directory on a buildlet 37 | ping test whether a buildlet is alive and reachable 38 | push sync the repo of your pwd to the buildlet 39 | put put files on a buildlet 40 | put14 put Go 1.4 in place 41 | puttar extract a tar.gz to a buildlet 42 | rm delete files or directories 43 | run run a command on a buildlet 44 | 45 | To list all the builder types available, run "create" with no arguments: 46 | 47 | $ gomote create 48 | (tons of builder types) 49 | 50 | The "gomote run" command has many of its own flags: 51 | 52 | $ gomote run -h 53 | create usage: gomote run [run-opts] [args...] 54 | -builderenv string 55 | Optional alternate builder to act like. Must share the same 56 | underlying buildlet host type, or it's an error. For 57 | instance, linux-amd64-race or linux-386-387 are compatible 58 | with linux-amd64, but openbsd-amd64 and openbsd-386 are 59 | different hosts. 60 | -debug 61 | write debug info about the command's execution before it begins 62 | -dir string 63 | Directory to run from. Defaults to the directory of the 64 | command, or the work directory if -system is true. 65 | -e value 66 | Environment variable KEY=value. The -e flag may be repeated 67 | multiple times to add multiple things to the environment. 68 | -path string 69 | Comma-separated list of ExecOpts.Path elements. The special 70 | string 'EMPTY' means to run without any $PATH. The empty 71 | string (default) does not modify the $PATH. Otherwise, the 72 | following expansions apply: the string '$PATH' expands to 73 | the current PATH element(s), the substring '$WORKDIR' 74 | expands to the buildlet's temp workdir. 75 | -system 76 | run inside the system, and not inside the workdir; this is implicit if cmd starts with '/' 77 | ``` 78 | 79 | ## Tricks 80 | 81 | ### Windows 82 | 83 | ``` 84 | $ gomote run -path '$PATH,$WORKDIR/go/bin' -e 'GOROOT=c:\workdir\go' user-bradfitz-windows-amd64-gce-0 go/bin/go.exe test cmd/go -short 85 | ``` 86 | 87 | ### Subrepos on Windows 88 | 89 | ``` 90 | $ tar -C ~/src/ -zc golang.org/x/tools | gomote puttar -dir=gopath/src $MOTE 91 | $ gomote run -e 'GOPATH=c:/workdir/gopath' $MOTE go/bin/go test -run=TestFixImportsVendorPackage golang.org/x/tools/imports 92 | ``` 93 | 94 | ### Subrepos on Unix 95 | 96 | Testing golang.org/x/sys/unix on $MOTE 97 | 98 | ``` 99 | $ tar -C $GOPATH/src/ -zc golang.org/x/sys/unix | gomote puttar -dir=gopath/src $MOTE 100 | $ gomote run -e 'GOPATH=/tmp/workdir/gopath' $MOTE go/bin/go test -v golang.org/x/sys/unix 101 | ``` 102 | 103 | ## About Buildlets 104 | 105 | http://farmer.golang.org/builders lists information about how each buildlet is deployed and configured. 106 | The information is from golang.org/x/build/dashboard and golang.org/x/build/env. 107 | -------------------------------------------------------------------------------- /docs/CustomPprofProfiles.md: -------------------------------------------------------------------------------- 1 | Originally published at https://rakyll.org/custom-profiles/. 2 | 3 | ---- 4 | 5 | Go provides several pprof profiles out of thet box to gather 6 | profiling data from Go programs. 7 | 8 | The builtin profiles provided by the [runtime/pprof](https://golang.org/pkg/runtime/pprof/) package: 9 | 10 | * **profile**: CPU profile determines where a program spends its time while actively consuming CPU cycles (as opposed while sleeping or waiting for I/O). 11 | * **heap**: Heap profile reports the currently live allocations; used to monitor current memory usage or check for memory leaks. 12 | * **threadcreate**: Thread creation profile reports the sections of the program that lead the creation of new OS threads. 13 | * **goroutine**: Goroutine profile report the stack traces of all current goroutines. 14 | * **block**: Block profile show where goroutines block waiting on synchronization primitives (including timer channels). Block profile is not enabled by default; use runtime.SetBlockProfileRate to enable it. 15 | * **mutex**: Mutex profile reports the lock contentions. When you think your CPU is not fully utilized due to a mutex contention, use this profile. Mutex profile is not enabled by default, see runtime.SetMutexProfileFraction to enable. 16 | 17 | Additional to the builtin profiles, [runtime/pprof](https://golang.org/pkg/runtime/pprof/) package allows you to export your custom profiles, and instrument your code to record 18 | execution stacks that contributes to this profile. 19 | 20 | Imagine we have a blob server, and we are writing a Go client for it. And our users want to be able to profile the opened blobs on the client. We can create a profile and record the events of blob opening and closing, so the user can tell how many open blobs they are at any time. 21 | 22 | Here is a blobstore package that allows you to open some blobs. We will create a new custom profile and start 23 | recording execution stacks that contributes to opening of blobs: 24 | 25 | ``` go 26 | package blobstore 27 | 28 | import "runtime/pprof" 29 | 30 | var openBlobProfile = pprof.NewProfile("blobstore.Open") 31 | 32 | // Open opens a blob, all opened blobs need 33 | // to be closed when no longer in use. 34 | func Open(name string) (*Blob, error) { 35 | blob := &Blob{name: name} 36 | // TODO: Initialize the blob... 37 | 38 | openBlobProfile.Add(blob, 2) // add the current execution stack to the profile 39 | return blob, nil 40 | } 41 | ``` 42 | 43 | And once users want to close the blob, we need to remove the execution stack associated with the current blob from the profile: 44 | 45 | ```go 46 | // Close closes the blob and frees the 47 | // underlying resources. 48 | func (b *Blob) Close() error { 49 | // TODO: Free other resources. 50 | openBlobProfile.Remove(b) 51 | return nil 52 | } 53 | ``` 54 | 55 | And now, from the programs using this package, we should be able to retrieve `blobstore.Open` profile data and use our daily pprof tools to examine and visualize them. 56 | 57 | Let's write a small main program than opens some blobs: 58 | 59 | ``` 60 | package main 61 | 62 | import ( 63 | "fmt" 64 | "math/rand" 65 | "net/http" 66 | _ "net/http/pprof" // as a side effect, registers the pprof endpoints. 67 | "time" 68 | 69 | "myproject.org/blobstore" 70 | ) 71 | 72 | func main() { 73 | for i := 0; i < 1000; i++ { 74 | name := fmt.Sprintf("task-blob-%d", i) 75 | go func() { 76 | b, err := blobstore.Open(name) 77 | if err != nil { 78 | // TODO: Handle error. 79 | } 80 | defer b.Close() 81 | 82 | // TODO: Perform some wrork, write to the blob. 83 | }() 84 | } 85 | http.ListenAndServe("localhost:8888", nil) 86 | } 87 | ``` 88 | 89 | Start the server, then use go tool to read and visualize the profile data: 90 | 91 | ``` 92 | $ go tool pprof http://localhost:8888/debug/pprof/blobstore.Open 93 | (pprof) top 94 | Showing nodes accounting for 800, 100% of 800 total 95 | flat flat% sum% cum cum% 96 | 800 100% 100% 800 100% main.main.func1 /Users/jbd/src/hello/main.go 97 | ``` 98 | 99 | You will see that there are 800 open blobs and all openings are coming from main.main.func1. In this small example, there is nothing more to see, but in a complex server you can examine the hottest spots that works with an open blob and find out bottlenecks or leaks. -------------------------------------------------------------------------------- /docs/DesignDocuments.md: -------------------------------------------------------------------------------- 1 | # Go 1.1 2 | * [Scalable Scheduler](https://docs.google.com/document/d/1TTj4T2JO42uD5ID9e89oa0sLKhJYD0Y_kqxDv3I3XMw) 3 | * [net/http/cookiejar](https://groups.google.com/d/msg/golang-dev/ygDB3nbir00/rouknDcuyakJ) 4 | * [Function Calls](https://docs.google.com/document/d/1bMwCey-gmqZVTpRax-ESeVuZGmjwbocYs1iHplK-cjo/pub) 5 | 6 | # Go 1.2 7 | 8 | * [xml.Marshaler and Unmarshaler](http://golang.org/s/go12xml) 9 | * [encoding.TextMarshaler and Unmarshaler](http://golang.org/s/go12encoding) 10 | * [Runtime Symbol Table Format](http://golang.org/s/go12symtab) 11 | * [Field Selectors and Nil Checks](http://golang.org/s/go12nil) 12 | * [```x[i:j:k]``` Slice Syntax](http://golang.org/s/go12slice) 13 | * [Preemptive Scheduler](https://docs.google.com/document/d/1ETuA2IOmnaQ4j81AtTGT40Y4_Jr6_IDASEKg0t0dBR8/edit?usp=sharing) 14 | 15 | # Go 1.3 16 | 17 | * [Contiguous Stacks](https://docs.google.com/document/d/1wAaf1rYoM4S4gtnPh0zOlGzWtrZFQ5suE8qr2sD8uWQ/pub) 18 | * [Go 1.3 Linker Overhaul](https://golang.org/s/go13linker) 19 | * [Go 1.3 Native Client Support](https://docs.google.com/document/d/1oA4rs0pfk5NzUyA0YX6QsUEErNIMXawoscw9t0NHafo/pub) 20 | 21 | # Go 1.4 22 | 23 | * [Go channels on steroids](http://golang.org/s/go13chan) 24 | * [Go 1.4 “Internal” Packages](http://golang.org/s/go14internal) 25 | * [Go 1.4 src/pkg → src](http://golang.org/s/go14nopkg) 26 | * [Go 1.4 Custom Import Path Checking](http://golang.org/s/go14customimport) 27 | * [Go generate: A Proposal](http://golang.org/s/go1.4-generate) 28 | * [The syscall package](https://docs.google.com/a/golang.org/document/d/1QXzI9I1pOfZPujQzxhyRy6EeHYTQitKKjHfpq0zpxZs) 29 | * [Go 1.4 Subrepo Renaming](http://golang.org/s/go14subrepo) 30 | * [Go 1.4 Native Client Support for ARM](http://golang.org/s/go14naclarm) 31 | * [dev.cc branch plan](http://golang.org/s/dev.cc) 32 | 33 | # Go 1.5 34 | 35 | * [Go 1.5 Bootstrap Plan](https://golang.org/s/go15bootstrap) 36 | * [Go Compiler Overhaul](http://golang.org/s/go13compiler) 37 | * [Go Execution Tracer](http://goo.gl/eXjfeS) 38 | 39 | # Future Proposals 40 | 41 | * [New SSA Backend for the Go Compiler](https://docs.google.com/document/d/1szwabPJJc4J-igUZU4ZKprOrNRNJug2JPD8OYi3i1K0/edit?usp=sharing_eid) 42 | * [Go 1.4+ Garbage Collection (GC) Plan and Roadmap](http://golang.org/s/go14gc) 43 | * [Better GC and Memory Allocator for Go](https://docs.google.com/document/d/1HCPu3WKyCX3ZRYxmIMKTk0Ik1dePxKW1p02k3uhcft4/view) 44 | * [Groups Discussion](https://groups.google.com/d/topic/golang-dev/pwUh0BVFpY0/discussion) 45 | * [Precise GC Stack Roots](https://docs.google.com/document/d/13v_u3UrN2pgUtPnH4y-qfmlXwEEryikFu0SQiwk35SA/pub) 46 | * [Go 1.3 cmd/go and os/fsnotify](http://golang.org/s/go13fsnotify) 47 | * [Go 1.5 os/fsnotify API](http://goo.gl/MrYxyA) 48 | * [Simple Multi-Dimensional Slices (Tables)](https://docs.google.com/document/d/1eHm7KqfKP9_s4vR1zToxq-FBazdUQ9ZYi-YhcEtdfR0/edit) 49 | * [Go execution modes](https://docs.google.com/a/golang.org/document/d/1nr-TQHw_er6GOQRsF6T43GGhFDelrAP0NqSS_00RgZQ/edit) 50 | * [Building and distributing Go packages as shared libraries](https://docs.google.com/a/canonical.com/document/d/1PxhXNhsdqwBjteW7poqv4Vf3PhtTmYuQKkOk_JNWeh0/edit#heading=h.9hyi51rp3owq) 51 | * [NUMA-aware scheduler for Go](https://docs.google.com/document/d/1d3iI2QWURgDIsSR6G2275vMeQ_X7w-qxM2Vp7iGwwuM/pub) 52 | * [Go 1.5+ "External" Packages](https://docs.google.com/document/d/1CJnU6ZKvsp21B0lQwbJlKFt8Zz4EWscaCRy_EwK8ja8) 53 | 54 | # Other Tools 55 | * [Go Oracle](https://docs.google.com/document/d/1WmMHBUjQiuy15JfEnT8YBROQmEv-7K6bV-Y_K53oi5Y) 56 | * [Binding Go and Java](http://golang.org/s/gobind) 57 | * [Go Builder Plan](http://golang.org/s/builderplan) 58 | * [gomobile — a tool for building apps](https://docs.google.com/document/d/1cePOQ35PNEb_QqxnPAmBv0cEnAm7AQSGuz9wVeJ-lBs/edit) 59 | 60 | # Rejected Proposals 61 | * [Read-only Slices](https://docs.google.com/a/golang.org/document/d/1UKu_do3FRvfeN5Bb1RxLohV-zBOJWTzX0E8ZU1bkqX0/edit#heading=h.2wzvdd6vdi83), [Evaluation of read-only slices](https://docs.google.com/document/d/1-NzIYu0qnnsshMBpMPmuO21qd8unlimHgKjRD9qwp2A/edit) ([rejected](https://groups.google.com/d/msg/golang-dev/Y7j4B2r_eDw/Rkq-OtEsEBAJ)) 62 | * [Go 1.4: unsafe.Pointer arithmetic](https://docs.google.com/a/dempsky.org/document/d/1yyCMzE4YPfsXvnZNjhszaYNqavxHhvbY-OWPqdzZK30/pub) -------------------------------------------------------------------------------- /docs/PerfDashboard.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | [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) . 4 | 5 | # Builders 6 | 7 | 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. 8 | 9 | # Benchmarks 10 | 11 | The builders run benchmarks from the [x/benchmarks](https://golang.org/x/benchmarks) repo: 12 | * ` json `: marshals and unmarshals large json object, in several goroutines independently. 13 | * ` http `: http client and server serving "hello world", uses persistent connections and read/write timeouts. 14 | * ` 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. 15 | * ` build `: does 'go build -a std'. 16 | 17 | # Metrics 18 | 19 | Metrics collected are: 20 | * ` allocated `: amount of memory allocated, per iteration, in bytes 21 | * ` allocs `: number of memory allocations, per iteration 22 | * ` cputime `: total CPU time (user+sys from time Unix utility output), can be larger than time when GOMAXPROCS>1, per iteration, in ns 23 | * ` gc-pause-one `: duration of a single garbage collector pause, in ns 24 | * ` gc-pause-total `: total duration of garbage collector pauses, per iteration, ns 25 | * ` latency-50/95/99 `: request latency percentile, in ns 26 | * ` rss `: max memory consumption as reported by OS, in bytes 27 | * ` sys-gc `: memory consumed by garbage collector metadata (` MemStats.GCSys `), in bytes 28 | * ` sys-heap `: memory consumed by heap (` MemStats.HeapSys `), in bytes 29 | * ` sys-other `: unclassified memory consumption (` MemStats.OtherSys `), in bytes 30 | * ` sys-stack `: memory consumed by stacks (` MemStats.StackSys `), in bytes 31 | * ` sys-total `: total memory allocated from OS (` MemStats.Sys `), in bytes 32 | * ` time `: real time (essentially the same as std Go benchmarks output), per iteration, in ns 33 | * ` virtual-mem `: virtual memory consumption as reported by OS, in bytes 34 | 35 | And for build benchmark: 36 | * ` binary-size `: size of the go command, in bytes 37 | * ` build-cputime `: CPU time spent on the build, in ns 38 | * ` build-rss `: max memory consumption of the build process as reported by OS, in bytes 39 | * ` build-time `: real time of the build, in ns 40 | 41 | # Profiles 42 | 43 | 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). 44 | 45 | # Perf Changes View 46 | 47 | The [view](http://build.golang.org/perf) allows to see aggregate information about significant performance changes caused by recent commits. 48 | 49 | Rows: 50 | * The first row shows difference between the latest release and tip. 51 | * The rest of the rows show deltas caused by individual commits. 52 | 53 | Columns: 54 | * The first column is commit hash. 55 | * Second - number of benchmarks that were executed for the commit to far. 56 | * Third - metric name, or the special 'failure' metric for build/runtime crashes. 57 | * Fourth - negative deltas. 58 | * Fifth - positive deltas. 59 | * The rest describe commit. 60 | 61 | You can click on any positive/negative delta to see details about the change. 62 | -------------------------------------------------------------------------------- /docs/SuccessStories.md: -------------------------------------------------------------------------------- 1 | # 웹에서 발췌한 Go 성공 사례들 2 | 3 | * [The Way of the Gopher - Making the Switch from Node.js to Golang](https://medium.com/@theflapjack103/the-way-of-the-gopher-6693db15ae1f) 4 | * [Moving a team from Scala to Go](http://jimplush.com/talk/2015/12/19/moving-a-team-from-scala-to-golang/) 5 | * [400 Days of Go](http://www.philipotoole.com/400-days-of-go/) 6 | * [From Python to Go: Migrating our entire API](https://blog.repustate.com/migrating-entire-api-go-python/) 7 | * [Our Experience with Golang](https://www.scriptrock.com/blog/our-experience-with-golang) 8 | * [The Reliability of Go](http://andrewwdeane.blogspot.de/2013/05/the-reliability-of-go.html) 9 | * [A Go Redirection Service](http://blog.dnsimple.com/a-golang-redirection-service/) 10 | * [pool.ntp.org DNS server in Go](http://news.ntppool.org/2012/10/new-dns-server.html) 11 | * [Juju at Canonical](http://www.reddit.com/r/programming/comments/18atce/juju_canonical_109k_lines_of_go_code/) 12 | * [Go at bitly](http://word.bitly.com/post/29550171827/go-go-gadget) 13 | * [NSQ: realtime distributed message processing at scale](http://word.bitly.com/post/33232969144/nsq) 14 | * [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/) 15 | * [Why I Like Go](https://gist.github.com/freeformz/4746274) 16 | * [Why I Program in Go](http://tech.t9i.in/2013/01/why-program-in-go/) 17 | * [dl.google.com now served by Go](https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/BNUNbKSypE0) 18 | * [Google's Go Programming Language Grows Up: Now What?](http://readwrite.com/2012/03/29/googles-go-programming-languag/) 19 | * [Moving to Go](http://blog.toggl.com/2012/09/moving-to-go/) 20 | * [Rob Pike: Why Learn Go?](http://www.youtube.com/watch?v=FTl0tl9BGdc) 21 | * [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) 22 | * [Another go at the Next Big Language](http://dave.cheney.net/2012/09/03/another-go-at-the-next-big-language) 23 | * [@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) 24 | * [@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) 25 | * [Will Go be the new go-to programming language?](http://gigaom.com/cloud/will-go-be-the-new-go-to-programming-language/) 26 | * [Dr. Dobb's: Why Not Go?](http://www.drdobbs.com/open-source/why-not-go/240005062) 27 | * [Google I/O 2012: Go in production](http://www.youtube.com/watch?v=kKQLhGZVN4A) 28 | * [Go at Cockroach Labs](https://www.cockroachlabs.com/blog/why-go-was-the-right-choice-for-cockroachdb/), [cockroachdb/cockroach](https://github.com/cockroachdb/cockroach) 29 | * [Go at Novartis](https://plus.google.com/114945221884326152379/posts/d1SVaqkRyTL) 30 | * [Go at the BBC](http://www.quora.com/Go-programming-language/Is-Google-Go-ready-for-production-use/answer/Kunal-Anand) 31 | * [Go at SoundCloud](http://backstage.soundcloud.com/2012/07/go-at-soundcloud/) 32 | * [Go at Moovweb](https://groups.google.com/forum/#!topic/golang-nuts/MeiTNnGhLg8/discussion) 33 | * [Building StatHat with Go](http://blog.golang.org/2011/12/building-stathat-with-go.html) 34 | * [Go at CloudFlare](http://blog.cloudflare.com/go-at-cloudflare) 35 | * [Why you PHP guys should learn Golang](http://www.mikespook.com/2012/08/why-you-php-guys-should-learn-golang/) 36 | * [I/O BootCamp 2011: Real World Go](http://www.youtube.com/watch?v=7QDVRowyUQA) 37 | * [Go at Heroku](http://blog.golang.org/2011/04/go-at-heroku.html) 38 | * [Go at Basecamp](https://signalvnoise.com/posts/3897-go-at-basecamp) 39 | * [Go at Streetspotr](https://thcyron.de/2015/go-at-streetspotr.html) 40 | * [Confession From A Go Programer](https://zeta.si/page/Confession-From-A-Go-Programer) 41 | * [Why we chose Go over C for updating embedded Linux devices](https://mender.io/blog/why-did-we-choose-golang-over-c) 42 | * [List of Tech Migrations](http://kokizzu.blogspot.com/2016/12/list-of-tech-migrations.html) 43 | * [Making the move from Scala to Go, and why we’re not going back](https://movio.co/blog/migrate-Scala-to-Go/) 44 | 45 | [Go 사용자들](GoUsers)을 살펴보세요 -------------------------------------------------------------------------------- /docs/Learn.md: -------------------------------------------------------------------------------- 1 | In addition to the resources available [at golang.org](http://golang.org/doc/#learning) there are a range of community-driven initiatives: 2 | 3 | * [The Little Go Book](http://openmymind.net/The-Little-Go-Book/) 4 | * [Exercism.io - Go](http://exercism.io/languages/go) - Online code exercises for Go for practice and mentorship. 5 | * [Learn Go in an Hour - Video](https://www.youtube.com/watch?v=CF9S4QZuV30) _2015-02-15_ 6 | * [Learning to Program in Go](https://www.youtube.com/playlist?list=PLei96ZX_m9sVSEXWwZi8uwd2vqCpEm4m6), a multi-part video training class. 7 | * [Pluralsight Classes for Go](http://www.pluralsight.com/tag/golang) - A growing collection of (paid) online classes. 8 | * [Ardan Labs Training](https://www.ardanlabs.com/) - Commercial, live instruction for Go programming. 9 | * [O'Reilly Go Fundamentals](http://shop.oreilly.com/category/learning-path/go-fundamentals.do) - Video learning path for Go programming. 10 | * [Go By Example](http://gobyexample.com/) provides a series of annotated code snippets. 11 | * [Learn Go in Y minutes](http://learnxinyminutes.com/docs/go/) is a top-to-bottom walk-through of the language. 12 | * [Workshop-Go](https://github.com/sendwithus/workshop-go) - Startup Slam Go Workshop - examples and slides. 13 | * [Go Fragments](http://www.gofragments.net/) - A collection of annotated Go code examples. 14 | * [50 Shades of Go: Traps, Gotchas, Common Mistakes for New Golang Devs](http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/index.html) 15 | * [Free Go Language Workshop](https://www.frameworktraining.co.uk/go-language-free-training-workshop/) Framework Training is running regular free BYOD workshops in London, UK 16 | * [GoingGo.net](http://www.goinggo.net/) - A collection of videos and articles for learning Go. 17 | * [Golang Tutorials](http://golangtutorials.blogspot.com/2011/05/table-of-contents.html) - A free online class. 18 | * Rob Pike's 2011 three day course - [Day 1](http://go.googlecode.com/hg-history/release-branch.r60/doc/GoCourseDay1.pdf), [Day 2](http://go.googlecode.com/hg-history/release-branch.r60/doc/GoCourseDay2.pdf), [Day 3](http://go.googlecode.com/hg-history/release-branch.r60/doc/GoCourseDay3.pdf) (*links are broken*, use the archived links from the wayback machine. [Day 1][wbday1], [Day 2][wbday2], [Day 3][wbday3]) 19 | * [The Go Bridge Foundry](https://github.com/gobridge) - A member of the [Bridge Foundry](http://bridgefoundry.org/) family, offering a complete set of free Go training materials with the goal of bringing Go to under-served communities. 20 | * [Golangbot](https://golangbot.com/learn-golang-series/) - Tutorials to get started with programming in Go. 21 | * [Master Go](https://appliedgo.com/p/mastergo/) - A paid online video course on Go for developers 22 | * [Learn to Create Web Applications using Go](https://www.usegolang.com/) - A paid online video course and book about Web programming with Go 23 | * [Learn Go Programming](https://blog.learngoprogramming.com) - Weekly visual and concise tutorials for programming in Go. 24 | * [Gophercises](https://gophercises.com/) - coding exercises for budding gophers 25 | * [Algorithms to Go](http://yourbasic.org/) - Texts about algorithms and Go, with plenty of code examples. 26 | * [Games With Go](http://gameswithgo.org/) - Video series teaching programming fundamentals with game related projects. 27 | * [Go Language Tutorials](https://www.cybrhome.com/topic/go-language-tutorials) - List of popular sites, blogs and tutorials for learning Go language. 28 | 29 | [wbday1]: http://web.archive.org/web/20160305024536/http://go.googlecode.com/hg-history/release-branch.r60/doc/GoCourseDay1.pdf 30 | [wbday2]: http://web.archive.org/web/20160305081012/http://go.googlecode.com/hg-history/release-branch.r60/doc/GoCourseDay2.pdf 31 | [wbday3]: http://web.archive.org/web/20160305075151/http://go.googlecode.com/hg-history/release-branch.r60/doc/GoCourseDay3.pdf 32 | 33 | Learning resources for specific topics: 34 | * [LearnConcurrency](LearnConcurrency) outlines a course of study of Go's concurrency model and patterns. 35 | * [LearnErrorHandling](LearnErrorHandling) links to resources about error handling in Go. 36 | * [LearnTesting](LearnTesting) links to resources about testing in Go. 37 | * [LearnServerProgramming](LearnServerProgramming) links to resources about server programming in Go. 38 | * [Hackr.io Golang Tutorials](https://hackr.io/tutorials/learn-golang) - Best Golang tutorials recommended by the programming community. 39 | 40 | Further reading: 41 | * [Newspaper](http://www.newspaper.io) is a topic based newsfeed for slack. Built on Go 42 | -------------------------------------------------------------------------------- /docs/GitHubCodeLayout.md: -------------------------------------------------------------------------------- 1 | ## Introduction 2 | 3 | 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 `". 4 | 5 | 6 | ## Code Layout 7 | 8 | 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 `. 9 | 10 | Your code layout would look like this: 11 | 12 | ``` 13 | $GOPATH/ 14 | src/ 15 | github.com/ 16 | jmcvetta/ 17 | useless/ 18 | .git/ 19 | useless.go 20 | useless_test.go 21 | README.md 22 | uselessd/ 23 | .git/ 24 | uselessd.go 25 | uselessd_test.go 26 | README.md 27 | ``` 28 | 29 | Each folder under ` src/github.com/jmcvetta/ ` is the root of a separate git checkout. 30 | 31 | 32 | ## $GOPATH 33 | 34 | 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). 35 | 36 | 37 | ## Note for Eclipse Users 38 | 39 | 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. 40 | 41 | 42 | ### Setup the Workspace 43 | 44 | 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: 45 | 46 | ```sh 47 | cd ~/workspace # Standard location for Eclipse workspace 48 | mkdir mygo # Create your Go workspace 49 | export GOPATH=~/workspace/mygo # GOPATH = Go workspace 50 | cd $GOPATH 51 | mkdir -p src/github.com/jmcvetta 52 | cd src/github.com/jmcvetta 53 | git clone git@github.com:jmcvetta/useless.git 54 | git clone git@github.com:jmcvetta/uselessd.git 55 | ``` 56 | 57 | ## Libraries 58 | 59 | 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 `: 60 | 61 | ```Go 62 | package useless 63 | 64 | func Foobar() string { 65 | return "Foobar!" 66 | } 67 | ``` 68 | 69 | 70 | ## Applications 71 | 72 | An application - Go code that will be compiled into an executable command - always defines ` package main ` with a ` main() ` function. 73 | 74 | So ` uselessd.go ` looks like this: 75 | 76 | ```Go 77 | package main 78 | 79 | import ( 80 | "net/http" 81 | 82 | "golang.org/x/net/websocket" 83 | "github.com/jmcvetta/useless" 84 | ) 85 | 86 | func main() { 87 | http.Handle("/useless", websocket.Handler(func(ws *websocket.Conn) { 88 | ws.Write([]byte(useless.Foobar())) 89 | })) 90 | http.ListenAndServe(":3000", nil) 91 | } 92 | ``` 93 | 94 | 95 | ## Dependencies 96 | 97 | Your project will probably depend on some existing packages. The application above depends upon ` golang.org/x/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. 98 | 99 | See the output of "` go help packages `" for a full explanation of the "` ... `" syntax. 100 | 101 | 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. 102 | 103 | ## Build 104 | 105 | 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 `". 106 | 107 | To compile ` uselessd.go ` and its dependencies into an executable, use the command "` go build ...uselessd `". 108 | 109 | ## Example Code 110 | 111 | FWIW all the repo addresses on this page are real, and the ` uselessd ` application should compile if you follow the directions above. 112 | -------------------------------------------------------------------------------- /docs/Benchmarks.md: -------------------------------------------------------------------------------- 1 | These are benchmarks collected from the community used to measure the effects of changes to the Go core (compiler, runtime, and libraries). They should have the following properties: 2 | 3 | - they matter; someone cares, perhaps in a dollars-and-cents way, that they run well 4 | - they are go-gettable and don't require customized steps for building the benchmark 5 | - they run under `go test -bench ...` 6 | - they run relatively quickly, ideally a single "run" takes less than a second (there should perhaps be a separate set of longer-running benchmarks) 7 | - their timings are not gratuitously noisy 8 | - they run cleanly in a restricted environment, such as a Docker or rkt container 9 | - they're not gratuitously redundant with other benchmarks already in the list; we don't need ten microbenchmarks of Go transcendental functions 10 | 11 | Information for each benchmark includes (or should include): 12 | 13 | - a short name for the benchmark 14 | - the path to `go get` the benchmark 15 | - a regexp for the benchmark suite excluding individual benchmarks that might be noisy, long-running, or redundant 16 | - (ideally) a contact person for questions about the benchmarks 17 | 18 | | short name | notes | go get path | benchmark regexp | contact | 19 | | ---------- | ----- | ----------- | ---------------- | ------- | 20 | | capnproto2 | | `zombiezen.com/go/capnproto2/` | `Benchmark(TextMovementBetweenSegments\|Growth_MultiSegment)` | | 21 | | ethereum_bitutil | | `github.com/ethereum/go-ethereum/common/bitutil` | `Benchmark(BaseTest2KB\|FastTest2KB\|Encoding4KBVerySparse)` | | 22 | | ethereum_core | | `github.com/ethereum/go-ethereum/core` | `BenchmarkChainRead_full_10k` | | 23 | | ethereum_corevm | | `github.com/ethereum/go-ethereum/core/vm` | `BenchmarkOpDiv128` | | 24 | | ethereum_ecies | | `github.com/ethereum/go-ethereum/crypto/ecies` | `BenchmarkGenSharedKeyP256` | | 25 | | ethereum_ethash | | `github.com/ethereum/go-ethereum/consensus/ethash` | `BenchmarkHashimotoLight` | | 26 | | ethereum_sha3 | | `github.com/ethereum/go-ethereum/crypto/sha3` | `BenchmarkSha3_224_MTU` | | 27 | | ethereum_storage | | `github.com/ethereum/go-ethereum/swarm/storage` | `BenchmarkJoin_8` | | 28 | | gonum_blas_native | | `gonum.org/v1/gonum/blas/gonum` | `Benchmark(DasumMediumUnitaryInc\|Dnrm2MediumPosInc)` | | 29 | | gonum_community | | `gonum.org/v1/gonum/graph/community/` | `BenchmarkLouvainDirectedMultiplex` | | 30 | | gonum_lapack_native | | `gonum.org/v1/gonum/lapack/gonum` | `BenchmarkDgeev/Circulant10` | | 31 | | gonum_mat | | `gonum.org/v1/gonum/mat` | `Benchmark(MulWorkspaceDense1000Hundredth\|ScaleVec10000Inc20)` | | 32 | | gonum_path | | `gonum.org/v1/gonum/graph/path/` | `Benchmark(AStarUndirectedmallWorld_10_2_2_2_Heur\|Dominators/nested_if_n256)` | | 33 | | gonum_topo | | `gonum.org/v1/gonum/graph/topo/` | `Benchmark(TarjanSCCGnp_1000_half\|TarjanSCCGnp_10_tenth)` | | 34 | | gonum_traverse | | `gonum.org/v1/gonum/graph/traverse/` | `BenchmarkWalkAllBreadthFirstGnp_(10\|1000)_tenth` | | 35 | | hugo_helpers | | `github.com/gohugoio/hugo/helpers` | `Benchmark(StripHTML\|ReaderContains)` | | 36 | | hugo_hugolib | | `github.com/gohugoio/hugo/hugolib` | `BenchmarkParsePage` | | 37 | | hugo_hugolib_sitebuilding | | `github.com/gohugoio/hugo/hugolib` | `BenchmarkSiteBuilding/YAML,num_pages=10,num_tags=10,tags_per_page=20,shortcodes,render-12` | | 38 | | k8s_api | | `k8s.io/kubernetes/pkg/api/testing` | `BenchmarkEncodeCodecFromInternalProtobuf` | | 39 | | minio | | `github.com/minio/minio/cmd` | `BenchmarkGetObject5MbFS` | | 40 | | semver | | `github.com/Masterminds/semver` | `BenchmarkValidateVersionTildeFail` | | 41 | | spexs2 | | `github.com/egonelbre/spexs2/_benchmark/` | `BenchmarkRun/10k/1` | | 42 | | uuid | | `github.com/satori/go.uuid/` | `Benchmark(NewV5\|MarshalToString)` | | 43 | 44 | There is a [benchmark runner](https://github.com/dr2chase/bent) that automates downloading, building, and running these benchmarks under various (user-defined) configurations. Benchmarking noise on Linux can be somewhat reduced with [perflock](https://github.com/aclements/perflock). 45 | 46 | A few have been proposed but have so far failed to make the cut (for fetch, build, or noise problems): 47 | 48 | | short name | notes | go get path | benchmark regexp | contact | 49 | | ---------- | ----- | ----------- | ---------------- | ------- | 50 | | eolian_dsp | | `buddin.us/eolian/dsp` | `Benchmark` | | 51 | | ethereum_trie | | `github.com/ethereum/go-ethereum/trie` | `Benchmark` | | 52 | | ethereum_whisperv5 | | `github.com/ethereum/go-ethereum/whisper/whisperv5` | `Benchmark` | | 53 | | k8s_schedulercache | | `k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache` | `Benchmark` | | 54 | | kanzi | | `github.com/flanglet/kanzi/go/src/kanzi/benchmark` | `Benchmark` | | 55 | | uber_zap | | `github.com/uber-go/zap/benchmarks` | `Benchmark` | | 56 | -------------------------------------------------------------------------------- /docs/vgo.md: -------------------------------------------------------------------------------- 1 | ## Table of Contents 2 | 3 | * [Initial paper](#initial-paper) 4 | * [Current state](#current-state) 5 | * [Comment Threads](#comment-threads) 6 | * [Blog posts](#blog-posts) 7 | * [Presentations](#presentations) 8 | * [Videos](#videos) 9 | * [Questions](#questions) 10 | * [Projects Related to vgo](#projects-related-to-vgo) 11 | 12 | This document collects thoughts and notes about vgo from the Gophers [#vgo](https://gophers.slack.com/messages/vgo) channel. Invites to Gophers Slack from [here](https://invite.slack.golangbridge.org/). 13 | 14 | ### Initial paper 15 | 16 | The **initial paper** can be read here [https://research.swtch.com/vgo](https://research.swtch.com/vgo). 17 | 18 | The **proposal** can be found here [https://github.com/golang/go/issues/24301](https://github.com/golang/go/issues/24301). 19 | 20 | The **reference implementation**: [https://go.googlesource.com/vgo/](https://go.googlesource.com/vgo/) and mirrored on Github here: [https://github.com/golang/vgo](https://github.com/golang/vgo). 21 | 22 | The **[Go issue tracker](https://golang.org/issues)** is used to track bugs / feature requests for vgo. The issue titles need to start with `x/vgo` so that they can be automatically categorized. You can read the [existing issues here](https://golang.org/issues?q=is%3Aopen+is%3Aissue+milestone%3Avgo). 23 | 24 | *** 25 | 26 | ### Current state 27 | 28 | Currently vgo is in active development / prototype phase. It has some rough edges, changes will happen at a rapid pace. You are encouraged to try vgo and give your feedback, share your experience with it, and contribute to it. 29 | 30 | For any production workloads, use [dep](https://github.com/golang/dep), or migrate to it if you have not done so already. 31 | 32 | vgo will be merged in the Go tree and replace dep at a later date, assuming the proposal is accepted. 33 | 34 | *** 35 | 36 | ### Comment Threads 37 | 38 | These are threads that have been created from the initial reference manifest for vgo: 39 | 40 | - **golang-nuts ML:** [Go += Package Versioning](https://groups.google.com/forum/#!topic/golang-nuts/jFPz5yZCPcQ) 41 | 42 | - **golang-dev ML:** [Go += Package Versioning](https://groups.google.com/d/topic/golang-dev/MNQwgYHMEcY/discussion), [vgo & semantic import versioning](https://groups.google.com/d/topic/golang-dev/Plc42fslQEk/discussion), [vgo and vendoring](https://groups.google.com/forum/#!topic/golang-dev/FTMScX1fsYk) 43 | - **HackerNews posts:** https://news.ycombinator.com/from?site=swtch.com 44 | - **Reddit:** https://www.reddit.com/domain/research.swtch.com/ 45 | 46 | - **vgo & vendoring:** https://groups.google.com/forum/#!topic/golang-dev/FTMScX1fsYk 47 | - **vgo & semantic import versioning** https://groups.google.com/forum/#!topic/golang-dev/Plc42fslQEk 48 | 49 | *** 50 | 51 | ### Blog posts 52 | 53 | - [Thoughts on vgo and dep](https://sdboyer.io/blog/vgo-and-dep/) 54 | - [Exploring vgo](https://www.calhoun.io/exploring-vgo/) 55 | - [Semantic Import Versioning in the wild](http://blog.ezyang.com/2018/02/semantic-import-versioning-in-the-wild/) 56 | - [Diving into vgo from the Golang project](https://www.wolfe.id.au/2018/03/01/diving-into-vgo-from-the-golang-project/) 57 | - [A Proposal for Package Versioning in Go](https://blog.golang.org/versioning-proposal) 58 | *** 59 | 60 | ### Presentations 61 | 62 | - [Repeatable Builds with vgo](https://cda.ms/jD) 63 | 64 | *** 65 | 66 | ### Videos 67 | 68 | - [1-Using vgo for Go Dependency Management](https://www.gophersnacks.com/programs/using-vgo-for-go-dependency-management) by Brian Ketelsen 69 | - [2-Adding External Dependencies with vgo](https://www.gophersnacks.com/programs/adding-external-dependencies-with-vgo) 70 | - [Building Predictability into Your Pipeline](https://www.youtube.com/watch?v=sbrZfPgNmfw) with Russ Cox, Jess Frazelle, Sam Boyer, Pete Garcin. 71 | 72 | *** 73 | 74 | ### Projects Related to vgo 75 | 76 | - [Athens](https://github.com/gomods/athens) - A proxy server for vgo 77 | - [vgo-docker-example](https://github.com/elithrar/vgo-docker-example) - An example of how to use vgo + Docker together. 78 | 79 | *** 80 | 81 | ### Questions 82 | 83 | | Question | Answer | 84 | | ------------- | ------------- | 85 | | Hitting GitHub API rate limits? | Create a token and add it to .netrc, see [related issue](https://golang.org/issues/23955) | 86 | | How does vgo handles dependencies of older, discarded versions [link](https://gophers.slack.com/archives/C9BMAAFFB/p1519493604000033)? | [https://github.com/zeebo/vgo-test-version-selection](https://github.com/zeebo/vgo-test-version-selection) | 87 | | Why are major versions in import paths? | https://groups.google.com/forum/#!topic/golang-dev/Plc42fslQEk | 88 | | How to `go get` so that I can run a program, not download a library? | https://gophers.slack.com/archives/C9BMAAFFB/p1519687366000101 | 89 | | What's the best way to maintain a package repository that have the major version in the import path? | https://groups.google.com/d/topic/golang-nuts/nS6ST60dwF8/discussion, https://groups.google.com/d/topic/golang-nuts/VREgKrQRFcY/discussion | -------------------------------------------------------------------------------- /docs/Switch.md: -------------------------------------------------------------------------------- 1 | # Switch 2 | 3 | Spec: https://golang.org/ref/spec#Switch_statements 4 | 5 | Go's ` switch ` statements are pretty neat. For one thing, you don't need to break at the end of each case. 6 | 7 | ```go 8 | switch c { 9 | case '&': 10 | esc = "&" 11 | case '\'': 12 | esc = "'" 13 | case '<': 14 | esc = "<" 15 | case '>': 16 | esc = ">" 17 | case '"': 18 | esc = """ 19 | default: 20 | panic("unrecognized escape character") 21 | } 22 | ``` 23 | 24 | [src/pkg/html/escape.go](http://golang.org/src/pkg/html/escape.go#L178) 25 | 26 | ## Not just integers 27 | 28 | Switches work on values of any type. 29 | 30 | ```go 31 | switch syscall.OS { 32 | case "windows": 33 | sd = &sysDir{ 34 | Getenv("SystemRoot") + `\system32\drivers\etc`, 35 | []string{ 36 | "hosts", 37 | "networks", 38 | "protocol", 39 | "services", 40 | }, 41 | } 42 | case "plan9": 43 | sd = &sysDir{ 44 | "/lib/ndb", 45 | []string{ 46 | "common", 47 | "local", 48 | }, 49 | } 50 | default: 51 | sd = &sysDir{ 52 | "/etc", 53 | []string{ 54 | "group", 55 | "hosts", 56 | "passwd", 57 | }, 58 | } 59 | } 60 | ``` 61 | 62 | ## Missing expression 63 | 64 | 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: 65 | 66 | ```go 67 | func unhex(c byte) byte { 68 | switch { 69 | case '0' <= c && c <= '9': 70 | return c - '0' 71 | case 'a' <= c && c <= 'f': 72 | return c - 'a' + 10 73 | case 'A' <= c && c <= 'F': 74 | return c - 'A' + 10 75 | } 76 | return 0 77 | } 78 | ``` 79 | 80 | ## Break 81 | 82 | Go's ` switch ` statements ` break ` implicitly, but ` break ` is still useful: 83 | 84 | ```go 85 | command := ReadCommand() 86 | argv := strings.Fields(command) 87 | switch argv[0] { 88 | case "echo": 89 | fmt.Print(argv[1:]...) 90 | case "cat": 91 | if len(argv) <= 1 { 92 | fmt.Println("Usage: cat ") 93 | break 94 | } 95 | PrintFile(argv[1]) 96 | default: 97 | fmt.Println("Unknown command; try 'echo' or 'cat'") 98 | } 99 | ``` 100 | 101 | ## Fall through 102 | 103 | To fall through to a subsequent case, use the ` fallthrough ` keyword: 104 | 105 | ```go 106 | // Unpack 4 bytes into uint32 to repack into base 85 5-byte. 107 | var v uint32 108 | switch len(src) { 109 | default: 110 | v |= uint32(src[3]) 111 | fallthrough 112 | case 3: 113 | v |= uint32(src[2]) << 8 114 | fallthrough 115 | case 2: 116 | v |= uint32(src[1]) << 16 117 | fallthrough 118 | case 1: 119 | v |= uint32(src[0]) << 24 120 | } 121 | ``` 122 | [src/pkg/encoding/ascii85/ascii85.go](http://golang.org/src/pkg/encoding/ascii85/ascii85.go#L43) 123 | 124 | The 'fallthrough' must be the last thing in the case; you can't write something like 125 | 126 | ```go 127 | switch { 128 | case f(): 129 | if g() { 130 | fallthrough // Does not work! 131 | } 132 | h() 133 | default: 134 | error() 135 | } 136 | ``` 137 | However, you can work around this by using a 'labeled' `fallthrough`: 138 | 139 | ```go 140 | switch { 141 | case f(): 142 | if g() { 143 | goto nextCase // Works now! 144 | } 145 | h() 146 | break 147 | nextCase: 148 | fallthrough 149 | default: 150 | error() 151 | } 152 | ``` 153 | ## Multiple cases 154 | 155 | If you want to use multiple values in the same case, use a comma-separated list. 156 | 157 | ```go 158 | func letterOp(code int) bool { 159 | switch chars[code].category { 160 | case "Lu", "Ll", "Lt", "Lm", "Lo": 161 | return true 162 | } 163 | return false 164 | } 165 | ``` 166 | ## Type switch 167 | 168 | With a type switch you can switch on the type of an interface value (only): 169 | 170 | ```go 171 | func typeName(v interface{}) string { 172 | switch v.(type) { 173 | case int: 174 | return "int" 175 | case string: 176 | return "string" 177 | default: 178 | return "unknown" 179 | } 180 | } 181 | ``` 182 | 183 | You can also declare a variable and it will have the type of each ` case `: 184 | 185 | ```go 186 | func do(v interface{}) string { 187 | switch u := v.(type) { 188 | case int: 189 | return strconv.Itoa(u*2) // u has type int 190 | case string: 191 | mid := len(u) / 2 // split - u has type string 192 | return u[mid:] + u[:mid] // join 193 | } 194 | return "unknown" 195 | } 196 | 197 | do(21) == "42" 198 | do("bitrab") == "rabbit" 199 | do(3.142) == "unknown" 200 | ``` 201 | 202 | ## Noop case 203 | 204 | Sometimes it useful to have cases that require no action. This can look confusing, because it can appear that both the noop case and the subsequent case have the same action, but isn't so. 205 | 206 | ```go 207 | func pluralEnding(n int) string { 208 | ending := "" 209 | 210 | switch n { 211 | case 1: 212 | default: 213 | ending = "s" 214 | } 215 | 216 | return ending 217 | } 218 | 219 | fmt.Sprintf("foo%s\n", pluralEnding(1)) == "foo" 220 | fmt.Sprintf("bar%s\n", pluralEnding(2)) == "bars" 221 | 222 | ``` 223 | --------------------------------------------------------------------------------