Fix formatting after import

Dave Day 2014-12-10 15:02:18 +11:00
parent 87f483adec
commit 0d6986a1f7
32 changed files with 432 additions and 406 deletions

@ -39,6 +39,11 @@ Sorted by publication date.
* ISBN: ---
* References: [site](http://jan.newmarch.name/go/)
* **Go: Up and Running**
* Author: Alan Harris
* Publication Date: April 2015 (est.)
* ISBN: 978-1-4493-7025-1
* **Go In Action**
* Authors: Brian Ketelsen, Erik St. Martin, and William Kennedy
* Publication Date: Summer 2015 (est.)

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

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

@ -12,9 +12,9 @@ You can view this as a supplement to http://golang.org/doc/effective_go.html.
## gofmt
Run [gofmt](http://golang.org/cmd/gofmt/) on your code to automatically fix the majority of mechanical style issues. Almost all Go code in the wild uses ` gofmt `. The rest of this document addresses non-mechanical style points.
Run [gofmt](http://golang.org/cmd/gofmt/) on your code to automatically fix the majority of mechanical style issues. Almost all Go code in the wild uses `gofmt`. The rest of this document addresses non-mechanical style points.
An alternative is to use [goimports](https://godoc.org/code.google.com/p/go.tools/cmd/goimports), a superset of ` gofmt ` which additionally adds (and removes) import lines as necessary.
An alternative is to use [goimports](https://godoc.org/code.google.com/p/go.tools/cmd/goimports), a superset of `gofmt` which additionally adds (and removes) import lines as necessary.
## Comment Sentences
@ -44,7 +44,7 @@ Error strings should not be capitalized (unless beginning with proper nouns or a
## Handle Errors
See http://golang.org/doc/effective_go.html#errors. Do not discard errors using ` _ ` variables. If a function returns an error, check it to make sure the function succeeded. Handle the error, return it, or, in truly exceptional situations, panic.
See http://golang.org/doc/effective_go.html#errors. Do not discard errors using `_` variables. If a function returns an error, check it to make sure the function succeeded. Handle the error, return it, or, in truly exceptional situations, panic.
## Imports
@ -54,15 +54,15 @@ Imports are organized in groups, with blank lines between them. The standard li
package main
import (
"fmt"
"hash/adler32"
"os"
"fmt"
"hash/adler32"
"os"
"appengine/user"
"appengine/foo"
"appengine/foo"
"appengine/user"
"code.google.com/p/x/y"
"github.com/foo/bar"
"code.google.com/p/x/y"
"github.com/foo/bar"
)
```
@ -76,8 +76,8 @@ The import . form can be useful in tests that, due to circular dependencies, can
package foo_test
import (
. "foo"
"bar/testutil" // also imports "foo"
"bar/testutil" // also imports "foo"
. "foo"
)
```
@ -89,9 +89,9 @@ Try to keep the normal code path at a minimal indentation, and indent the error
```
if err != nil {
// error handling
// error handling
} else {
// normal code
// normal code
}
```
@ -99,8 +99,8 @@ Instead, write
```
if err != nil {
// error handling
return // or continue, etc.
// error handling
return // or continue, etc.
}
// normal code
```
@ -109,10 +109,10 @@ If the if statement has an initialization statement that, such as
```
if x, err := f(); err != nil {
// error handling
return
// error handling
return
} else {
// use x
// use x
}
```
@ -121,8 +121,8 @@ then this may require moving the short variable declaration to its own line:
```
x, err := f()
if err != nil {
// error handling
return
// error handling
return
}
// use x
```
@ -143,7 +143,7 @@ Comments are typically wrapped before no more than 80 characters, not because it
## Mixed Caps
See http://golang.org/doc/effective_go.html#mixed-caps. This applies even when it breaks conventions in other languages. For example an unexported constant is ` maxLength ` not ` MaxLength ` or ` MAX_LENGTH `.
See http://golang.org/doc/effective_go.html#mixed-caps. This applies even when it breaks conventions in other languages. For example an unexported constant is `maxLength` not `MaxLength` or `MAX_LENGTH`.
## Named Result Parameters
@ -162,14 +162,14 @@ func (n *Node) Parent2() (*Node, error)
On the other hand, if a function returns two or three parameters of the same type, or if the meaning of a result isn't clear from context, adding names may be useful. For example:
```go
func (f *Foo) Location() (float64, float64, error)```
func (f *Foo) Location() (float64, float64, error)
```
is less clear than
```go
// Location returns f's latitude and longitude.
// Negative values mean south and west, respectively.
func (f *Foo) Location() (lat, long float64, err error)```
func (f *Foo) Location() (lat, long float64, err error)
```
Naked returns are okay if the function is a handful of lines. Once it's a medium-sized function, be explicit with your return values. Corollary: it's not worth it to name result parameters just because it enables you to use naked returns. Clarity of docs is always more important than saving a line or two in your function.
@ -205,7 +205,7 @@ All references to names in your package will be done using the package name, so
## Pass Values
Don't pass pointers as function arguments just to save a few bytes. If a function refers to its argument ` x ` only as ` *x ` throughout, then the argument shouldn't be a pointer. Common instances of this include passing a pointer to a string (` *string `) or a pointer to an interface value (` *io.Reader `). In both cases the value itself is a fixed size and can be passed directly. This advice does not apply to large structs, or even small structs that might grow.
Don't pass pointers as function arguments just to save a few bytes. If a function refers to its argument `x` only as `*x` throughout, then the argument shouldn't be a pointer. Common instances of this include passing a pointer to a string (`*string`) or a pointer to an interface value (`*io.Reader`). In both cases the value itself is a fixed size and can be passed directly. This advice does not apply to large structs, or even small structs that might grow.
## Receiver Names
@ -230,9 +230,9 @@ Choosing whether to use a value or pointer receiver on methods can be difficult,
Tests should fail with helpful messages saying what was wrong, with what inputs, what was actually got, and what was expected. It may be tempting to write a bunch of assertFoo helpers, but be sure your helpers produce useful error messages. Assume that the person debugging your failing test is not you, and is not your team. A typical Go test fails like:
```
if got != tt.want {
t.Errorf("Foo(%q) = %d; want %d", tt.in, got, tt.want) // or Fatalf, if test can't test anything more past this point
}
if got != tt.want {
t.Errorf("Foo(%q) = %d; want %d", tt.in, got, tt.want) // or Fatalf, if test can't test anything more past this point
}
```
Note that the order here is actual != expected, and the message uses that order too. Some test frameworks encourage writing these backwards: 0 != x, "expected 0, got x", and so on. Go does not.
@ -242,8 +242,8 @@ If that seems like a lot of typing, you may want to write a table-driven test: h
Another common technique to disambiguate failing tests when using a test helper with different input is to wrap each caller with a different TestFoo function, so the test fails with that name:
```
func TestSingleValue(t *testing.T) { testHelper(t, []int{80}) }
func TestNoValues(t *testing.T) { testHelper(t, []int{}) }
func TestSingleValue(t *testing.T) { testHelper(t, []int{80}) }
func TestNoValues(t *testing.T) { testHelper(t, []int{}) }
```
In any case, the onus is on you to fail with a helpful message to whoever's debugging your code in the future.
@ -252,4 +252,4 @@ In any case, the onus is on you to fail with a helpful message to whoever's debu
Variable names in Go should be short rather than long. This is especially true for local variables with limited scope. Prefer c to lineCount. Prefer i to sliceIndex.
The basic rule: the further from its declaration that a name is used, the more descriptive the name must be. For a method receiver, one or two letters is sufficient. Common variables such as loop indices and readers can be a single letter (` i `, ` r `). More unusual things and global variables need more descriptive names.
The basic rule: the further from its declaration that a name is used, the more descriptive the name must be. For a method receiver, one or two letters is sufficient. Common variables such as loop indices and readers can be a single letter (`i`, `r`). More unusual things and global variables need more descriptive names.

@ -11,9 +11,9 @@ When new programmers start using Go or when old Go programmers start using a new
When iterating in Go, one might also be tempted to use a closure and goroutine to process data in parallel. For example, if you wanted to process values coming in from a channel in their own goroutines, you might write the following code:
```
for val := range values {
go func() {
fmt.Println(val)
}()
go func() {
fmt.Println(val)
}()
}
```
@ -24,9 +24,9 @@ The ` val ` variable in the above loop is actually a single variable that takes
The proper way to write that loop is:
```
for val := range values {
go func(val interface{}) {
fmt.Println(val)
}(val)
go func(val interface{}) {
fmt.Println(val)
}(val)
}
```
@ -36,10 +36,10 @@ It is also important to note that variables declared within the body of a loop a
```
for i := range valslice {
val := valslice[i]
go func() {
fmt.Println(val)
}()
val := valslice[i]
go func() {
fmt.Println(val)
}()
}
```
@ -47,9 +47,9 @@ Note that without executing this closure as a goroutine, the code runs as expect
```
for i := 1; i <= 10; i++ {
func() {
fmt.Println(i)
}()
func() {
fmt.Println(i)
}()
}
```

@ -1,6 +1,6 @@
# Introduction
Go is a great langage for CS majors. This page presents some university courses that uses Go.
Go is a great langage for CS majors. This page presents some university courses that use Go.
# Language

@ -24,6 +24,7 @@ See http://golang.org/s/builderplan
## Legacy Builders
These builders are configured and run manually. The goal is to migrate as many as possible over to the new system.
| **title** | **description** | **owner** | **notes** |
|:----------|:----------------|:----------|:----------|
| darwin-amd64 | 2011 Mac Mini, 2.4Ghz Core i5 | adg | Mac OS X 10.6 (10K549) |

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

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

@ -74,6 +74,7 @@ And finally, the Go file that uses the embedded slide:
```
/* data.go */
package bindata
func getDataSlices() ([]byte, []byte) // defined in slice.c
var A, B = getDataSlices()

@ -69,7 +69,7 @@ When the cross-compiler is build you should test that it works, both for a simpl
### Gotchas
If you haven't compiled a shared object of the go library, _libgo_, for your target you might want to compile your Go programs statically, just like _gc_ does, to include all what is needed to run your program. Do this by adding the _-static_ switch to gccgo. If you're unsure how your produced ELF file is liked, inspect it with _readelf -d ` <elf `>_ or _objdump -T ` <elf `>_.
If you haven't compiled a shared object of the go library, _libgo_, for your target you might want to compile your Go programs statically, just like _gc_ does, to include all what is needed to run your program. Do this by adding the _-static_ switch to gccgo. If you're unsure how your produced ELF file is liked, inspect it with _readelf -d `<elf>`_ or _objdump -T `<elf>`_.
## Build a cross-gccgo aware version of the Go tool

@ -44,7 +44,6 @@ Both Go and Eclipse use the term "workspace", but they use it to mean something
Let's assume we are starting from scratch. Initialize the two new repositories on Github, using the "Initialize this repository with a README" option so your repos can be cloned immediately. Then setup the project like this:
```sh
cd ~/workspace # Standard location for Eclipse workspace
mkdir mygo # Create your Go workspace
export GOPATH=~/workspace/mygo # GOPATH = Go workspace
@ -63,8 +62,9 @@ Conventionally, the name of the repository is the same as the name of the packag
package useless
func Foobar() string {
return "Foobar!"
}```
return "Foobar!"
}
```
# Applications
@ -77,18 +77,19 @@ So ` uselessd.go ` looks like this:
package main
import (
"net/http"
"net/http"
"code.google.com/p/go.net/websocket"
"github.com/jmcvetta/useless"
"code.google.com/p/go.net/websocket"
"github.com/jmcvetta/useless"
)
func main() {
http.Handle("/useless", websocket.Handler(func(ws *websocket.Conn) {
ws.Write([]byte(useless.Foobar()))
}))
http.ListenAndServe(":3000", nil)
}```
http.Handle("/useless", websocket.Handler(func(ws *websocket.Conn) {
ws.Write([]byte(useless.Foobar()))
}))
http.ListenAndServe(":3000", nil)
}
```
# Dependencies

@ -11,26 +11,26 @@ Struct field names must not include package qualifiers.
For example, take this struct with an embedded ` *bytes.Buffer ` field:
```
type S struct {
*bytes.Buffer
}
type S struct {
*bytes.Buffer
}
```
In Go 1.0 the compiler would (incorrectly) accept this struct literal:
```
s := S{
bytes.Buffer: new(bytes.Buffer),
}
s := S{
bytes.Buffer: new(bytes.Buffer),
}
```
Under Go 1.1 the compiler rejects this.
Instead you should use the field name without the package qualifier:
```
s := S{
Buffer: new(bytes.Buffer),
}
s := S{
Buffer: new(bytes.Buffer),
}
```
## Initialization loop
@ -40,26 +40,26 @@ The Go 1.1 compiler now better detects initialization loops.
For instance, the following code compiled under Go 1.0.
```
var funcVar = fn
var funcVar = fn
func fn() {
funcVar()
}
func fn() {
funcVar()
}
```
Such code must now use an ` init ` function for the variable assignment to avoid
the initialization loop.
```
var funcVar func()
var funcVar func()
func fn() {
funcVar()
}
func fn() {
funcVar()
}
func init() {
funcVar = fn
}
func init() {
funcVar = fn
}
```
In particular, this affects users of App Engine's [delay package](https://developers.google.com/appengine/docs/go/taskqueue/delay).
@ -70,12 +70,12 @@ In particular, this affects users of App Engine's [delay package](https://develo
Go 1.0 permitted fallthrough in the final case of a switch statement:
```
switch {
case false:
fallthrough // fall through to 'true' case
case true:
fallthrough // fall through to... nowhere?
}
switch {
case false:
fallthrough // fall through to 'true' case
case true:
fallthrough // fall through to... nowhere?
}
```
A language change affecting [return requirements](http://golang.org/doc/go1.1#return) led us to make the superfluous fallthrough illegal.
@ -88,7 +88,7 @@ The fix is to remove such statements from your code.
A compiler bug permitted function type declarations with parameters and return values of the same name. This would compile under Go 1.0:
```
type T func(a int) (a int)
type T func(a int) (a int)
```
Under Go 1.1, the compiler gives an error:

@ -308,7 +308,6 @@ _-- Rémy Oudompheng_
| Power Switch | To power cycle the board ?|
```
root@bpi01:/data/go13/src# cat ./buildgo.bash
#!/bin/bash
# use 1 CPU to avoid out of memory compilation issue.

@ -96,8 +96,8 @@ parentheses.
```
var (
i int
m float64
i int
m float64
)
```
@ -128,19 +128,19 @@ Within a function, a short declaration syntax is available with
` := ` .
```
v1 := v2 // C++11: auto v1 = v2;
v1 := v2 // C++11: auto v1 = v2;
```
This is equivalent to
```
var v1 = v2 // C++11: auto v1 = v2;
var v1 = v2 // C++11: auto v1 = v2;
```
Go permits multiple assignments, which are done in parallel. That is, first all of the values on the right-hand side are computed, and then these values are assigned to the variables on the left-hand side.
```
i, j = j, i // Swap i and j.
i, j = j, i // Swap i and j.
```
Functions may have multiple return values, indicated by a list in
@ -218,9 +218,9 @@ Thus, syntactically speaking, a structure and a pointer to a structure
are used in the same way.
```
type myStruct struct { i int }
var v9 myStruct // v9 has structure type
var p9 *myStruct // p9 is a pointer to a structure
type myStruct struct{ i int }
var v9 myStruct // v9 has structure type
var p9 *myStruct // p9 is a pointer to a structure
f(v9.i, p9.i)
```
@ -255,9 +255,9 @@ even to adjacent cases.
```
switch i {
case 0: // empty case body
case 0: // empty case body
case 1:
f() // f is not called when i == 0!
f() // f is not called when i == 0!
}
```
@ -266,7 +266,7 @@ But a ` case ` can have multiple values.
```
switch i {
case 0, 1:
f() // f is called if i == 0 || i == 1.
f() // f is called if i == 0 || i == 1.
}
```
@ -279,11 +279,11 @@ value is omitted it defaults to ` true `.
```
switch {
case i < 0:
f1()
f1()
case i == 0:
f2()
f2()
case i > 0:
f3()
f3()
}
```
@ -291,7 +291,7 @@ The ` defer ` statement may be used to call a function after the function contai
```
fd := open("filename")
defer close(fd) // fd will be closed when this function returns.
defer close(fd) // fd will be closed when this function returns.
```
<h2>Operators</h2>
@ -339,7 +339,7 @@ freely without requiring general implicit type conversion.
```
var a uint
f(a + 1) // untyped numeric constant "1" becomes typed as uint
f(a + 1) // untyped numeric constant "1" becomes typed as uint
```
The language does not impose any limits on the size of an untyped
@ -359,9 +359,9 @@ it reuses the preceding expression.
```
const (
red = iota // red == 0
blue // blue == 1
green // green == 2
red = iota // red == 0
blue // blue == 1
green // green == 2
)
```
@ -393,7 +393,7 @@ type velocity float64
var pos position = 218.0
var vel velocity = -9.8
pos += vel // INVALID: mismatched types position and velocity
pos += vel // INVALID: mismatched types position and velocity
// pos += position(vel) // Valid
```
@ -529,7 +529,8 @@ has a <em>receiver</em>. The receiver is similar to
the ` this ` pointer in a C++ class method.
```
type myType struct { i int }
type myType struct{ i int }
func (p *myType) Get() int { return p.i }
```
@ -545,9 +546,12 @@ derived from it. The new type is distinct from the builtin type.
```
type myInteger int
func (p myInteger) Get() int { return int(p) } // Conversion required.
func f(i int) { }
func f(i int) {}
var v myInteger
// f(v) is invalid.
// f(int(v)) is valid; int(v) has no defined methods.
```
@ -589,7 +593,11 @@ An anonymous field may be used to implement something much like a C++ child
class.
```
type myChildType struct { myType; j int }
type myChildType struct {
myType
j int
}
func (p *myChildType) Get() int { p.j++; return p.myType.Get() }
```
@ -629,8 +637,9 @@ not need to be any declared relationship between the two interfaces.
type myPrintInterface interface {
Print()
}
func f3(x myInterface) {
x.(myPrintInterface).Print() // type assertion to myPrintInterface
x.(myPrintInterface).Print() // type assertion to myPrintInterface
}
```
@ -644,7 +653,7 @@ programming similar to templates in C++. This is done by
manipulating values of the minimal interface.
```
type Any interface { }
type Any interface{}
```
Containers may be written in terms of ` Any `, but the caller
@ -800,9 +809,11 @@ can be useful with the ` go ` statement.
var g int
go func(i int) {
s := 0
for j := 0; j < i; j++ { s += j }
for j := 0; j < i; j++ {
s += j
}
g = s
}(1000) // Passes argument 1000 to the function literal.
}(1000) // Passes argument 1000 to the function literal.
```
Like C++11, but unlike prior versions of C++, Go defines a
@ -857,7 +868,7 @@ To use ` Manager2 `, given a channel to it:
```
func f4(ch chan<- Cmd2) int {
myCh := make(chan int)
c := Cmd2{ true, 0, myCh } // Composite literal syntax.
c := Cmd2{true, 0, myCh} // Composite literal syntax.
ch <- c
return <-myCh
}

@ -19,15 +19,15 @@ http://golang.org/pkg/sort/#Interface
- map() in Python: **map(lambda x:x\*2, range(100))**:
```
func Map(f interface{}, v interface{}) interface{} {
// Reflection to solve f and v types
}
func Map(f interface{}, v interface{}) interface{} {
// Reflection to solve f and v types
}
```
The reflect solution performance is really bad
- Polymorphic functions that operate on built-in generic types.
```
func KeyIntersection(a map[T1]T2, b map[T1]T2) map[T1]T2 {}
func KeyIntersection(a map[T1]T2, b map[T1]T2) map[T1]T2 {}
```
- Containers that must store non-interface values. (Various

@ -9,7 +9,9 @@ This is a complete Go webserver serving static files:
```
package main
import "net/http"
func main() {
panic(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))
}

@ -2,8 +2,8 @@
Given that you can assign a variable of any type to an ` interface{} `, often people will try code like the following.
```
var dataSlice []int = foo()
var interfaceSlice []interface{} = dataSlice
var dataSlice []int = foo()
var interfaceSlice []interface{} = dataSlice
```
This gets the error
```
@ -34,9 +34,9 @@ If you want a container for an arbitrary array type, and you plan on changing ba
If you really want a ` []interface{} ` because you'll be doing indexing before converting back, or you are using a particular interface type and you want to use its methods, you will have to make a copy of the slice.
```
var dataSlice []int = foo()
var interfaceSlice []interface{} = make([]interface{}, len(dataSlice))
for i, d := range dataSlice {
interfaceSlice[i] = d
}
var dataSlice []int = foo()
var interfaceSlice []interface{} = make([]interface{}, len(dataSlice))
for i, d := range dataSlice {
interfaceSlice[i] = d
}
```

19
Iota.md

@ -18,15 +18,16 @@ Here's one from Effective Go:
```
type ByteSize float64
const (
_ = iota // ignore first value by assigning to blank identifier
KB ByteSize = 1<<(10*iota)
MB
GB
TB
PB
EB
ZB
YB
_ = iota // ignore first value by assigning to blank identifier
KB ByteSize = 1 << (10 * iota)
MB
GB
TB
PB
EB
ZB
YB
)
```

@ -14,7 +14,7 @@ package sdl
// Arrange that main.main runs on main thread.
func init() {
runtime.LockOSThread()
runtime.LockOSThread()
}
// Main runs the main SDL service loop.
@ -22,9 +22,9 @@ func init() {
// Main does not return. If the binary needs to do other work, it
// must do it in separate goroutines.
func Main() {
for f = range mainfunc {
f()
}
for f = range mainfunc {
f()
}
}
// queue of work to run in main thread.
@ -32,20 +32,20 @@ var mainfunc = make(chan func())
// do runs f on the main thread.
func do(f func()) {
done := make(chan bool, 1)
mainfunc <- func() {
f()
done <- true
}
<-done
done := make(chan bool, 1)
mainfunc <- func() {
f()
done <- true
}
<-done
}
```
And then other functions you write in package sdl can be like
```
func Beep() {
do(func() {
// whatever must run in main thread
})
do(func() {
// whatever must run in main thread
})
}
```

@ -22,7 +22,8 @@ In general, when you have a variable of a type, you can pretty much call whateve
```
type List []int
func (l List) Len() int { return len(l) }
func (l List) Len() int { return len(l) }
func (l *List) Append(val int) { *l = append(*l, val) }
func main() {
@ -87,12 +88,14 @@ The concrete value stored in an interface is not addressable, in the same way th
```
type List []int
func (l List) Len() int { return len(l) }
func (l List) Len() int { return len(l) }
func (l *List) Append(val int) { *l = append(*l, val) }
type Appender interface {
Append(int)
}
func CountInto(a Appender, start, end int) {
for i := start; i <= end; i++ {
a.Append(i)
@ -102,6 +105,7 @@ func CountInto(a Appender, start, end int) {
type Lener interface {
Len() int
}
func LongEnough(l Lener) bool {
return l.Len()*10 > 42
}
@ -119,6 +123,6 @@ func main() {
CountInto(plst, 1, 10) // VALID: Identical receiver type
if LongEnough(plst) { // VALID: a *List can be dereferenced for the receiver
fmt.Printf(" - plst is long enough")
}
}
}
```

@ -82,7 +82,7 @@ To reuse the example above, the file ` ./publish/main.go ` may look something li
package main
import (
"flag"
"flag"
)
import "codesite.tld/authorName/Go-PublishingExample/epub"
@ -90,8 +90,8 @@ import "codesite.tld/authorName/Go-PublishingExample/epub"
var dir = flag.String("dir", ".", "Directory to publish")
func main() {
flag.Parse()
epub.Publish(*dir)
flag.Parse()
epub.Publish(*dir)
}
```

@ -11,68 +11,68 @@ By convention, no explicit panic() should be allowed to cross a package boundary
```
// A ParseError indicates an error in converting a word into an integer.
type ParseError struct {
Index int // The index into the space-separated list of words.
Word string // The word that generated the parse error.
Error error // The raw error that precipitated this error, if any.
Index int // The index into the space-separated list of words.
Word string // The word that generated the parse error.
Error error // The raw error that precipitated this error, if any.
}
// String returns a human-readable error message.
func (e *ParseError) String() string {
return fmt.Sprintf("pkg: error parsing %q as int", e.Word)
return fmt.Sprintf("pkg: error parsing %q as int", e.Word)
}
// Parse parses the space-separated words in in put as integers.
func Parse(input string) (numbers []int, err error) {
defer func() {
if r := recover(); r != nil {
var ok bool
err, ok = r.(error)
if !ok {
err = fmt.Errorf("pkg: %v", r)
}
}
}()
defer func() {
if r := recover(); r != nil {
var ok bool
err, ok = r.(error)
if !ok {
err = fmt.Errorf("pkg: %v", r)
}
}
}()
fields := strings.Fields(input)
numbers = fields2numbers(fields)
return
fields := strings.Fields(input)
numbers = fields2numbers(fields)
return
}
func fields2numbers(fields []string) (numbers []int) {
if len(fields) == 0 {
panic("no words to parse")
}
for idx, field := range fields {
num, err := strconv.Atoi(field)
if err != nil {
panic(&ParseError{idx, field, err})
}
numbers = append(numbers, num)
}
return
if len(fields) == 0 {
panic("no words to parse")
}
for idx, field := range fields {
num, err := strconv.Atoi(field)
if err != nil {
panic(&ParseError{idx, field, err})
}
numbers = append(numbers, num)
}
return
}
```
To demonstrate the behavior, consider the following main function:
```
func main() {
var examples = []string{
"1 2 3 4 5",
"100 50 25 12.5 6.25",
"2 + 2 = 4",
"1st class",
"",
}
var examples = []string{
"1 2 3 4 5",
"100 50 25 12.5 6.25",
"2 + 2 = 4",
"1st class",
"",
}
for _, ex := range examples {
fmt.Printf("Parsing %q:\n ", ex)
nums, err := Parse(ex)
if err != nil {
fmt.Println(err)
continue
}
fmt.Println(nums)
}
for _, ex := range examples {
fmt.Printf("Parsing %q:\n ", ex)
nums, err := Parse(ex)
if err != nil {
fmt.Println(err)
continue
}
fmt.Println(nums)
}
}
```

@ -29,6 +29,7 @@ If you find a project in this list that is dead or broken, please either mark it
## Build Tools
* [colorgo](https://github.com/songgao/colorgo) - Colorize go build output
* [dogo](https://github.com/liudng/dogo) - Monitoring changes in the source file and automatically compile and run (restart)
* [fileembed-go](https://bitbucket.org/rj/fileembed-go/) - This is a command-line utility to take a number of source files, and embed them into a Go package
* [gb](http://github.com/skelterjohn/go-gb) - A(nother) build tool for go, with an emphasis on multi-package projects
* [GG](http://www.manatlan.com/page/gg) - A build tool for Go in Go
@ -1092,6 +1093,7 @@ See also [SQLDrivers page](https://code.google.com/p/go-wiki/wiki/SQLDrivers).
* [OAuth Consumer](https://github.com/mrjones/oauth) - OAuth 1.0 consumer implementation
* [authcookie](https://github.com/dchest/authcookie) - Package authcookie implements creation and verification of signed authentication cookies.
* [totp](https://github.com/balasanjay/totp) - Time-Based One-Time Password Algorithm, specified in RFC 6238, works with Google Authenticator
* [otp](http://tristanwietsma.github.io/otp/) - HOTP and TOTP library with command line replacement for Google Authenticator
* [dgoogauth](https://github.com/dgryski/dgoogauth) - Go port of Google's Authenticator library for one-time passwords
* [go-http-auth](https://github.com/abbot/go-http-auth) - HTTP Basic and HTTP Digest authentication
* [httpauth](https://github.com/apexskier/httpauth) - HTTP session (cookie) based authentication and authorization

@ -10,15 +10,15 @@ A range clause provides a way to iterate over a array, slice, string, map, or ch
```
for k, v := range myMap {
log.Printf("key=%v, value=%v", k, v)
log.Printf("key=%v, value=%v", k, v)
}
for v := range myChannel {
log.Printf("value=%v", v)
log.Printf("value=%v", v)
}
for i, v := range myArray {
log.Printf("array value at [%d]=%v", i, v)
log.Printf("array value at [%d]=%v", i, v)
}
```
@ -50,7 +50,7 @@ The ` make ` and assignment look like they might work, but the value property of
```
items := make([]map[int]int, 10)
for i := range items {
items[i] = make(map[int]int, 1)
items[i] = make(map[int]int, 1)
items[i][1] = 2
}
```

@ -66,65 +66,63 @@ Here is a simpler approach that relies on the notion of elapsed time to provide
// }
//
package ratelimit
import "time"
type Ratelimiter struct {
rate int // conn/sec
last time.Time // last time we were polled/asked
rate int // conn/sec
last time.Time // last time we were polled/asked
allowance float64
allowance float64
}
// Create new rate limiter that limits at rate/sec
func NewRateLimiter(rate int) (*Ratelimiter, error) {
r := Ratelimiter{rate:rate, last:time.Now()}
r := Ratelimiter{rate: rate, last: time.Now()}
r.allowance = float64(r.rate)
return &r, nil
r.allowance = float64(r.rate)
return &r, nil
}
// Return true if the current call exceeds the set rate, false
// otherwise
func (r* Ratelimiter) Limit() bool {
func (r *Ratelimiter) Limit() bool {
// handle cases where rate in config file is unset - defaulting
// to "0" (unlimited)
if r.rate == 0 {
return false
}
// handle cases where rate in config file is unset - defaulting
// to "0" (unlimited)
if r.rate == 0 {
return false
}
rate := float64(r.rate)
now := time.Now()
elapsed := now.Sub(r.last)
r.last = now
r.allowance += float64(elapsed) * rate
rate := float64(r.rate)
now := time.Now()
elapsed := now.Sub(r.last)
r.last = now
r.allowance += float64(elapsed) * rate
// Clamp number of tokens in the bucket. Don't let it get
// unboundedly large
if r.allowance > rate {
r.allowance = rate
}
// Clamp number of tokens in the bucket. Don't let it get
// unboundedly large
if r.allowance > rate {
r.allowance = rate
}
var ret bool
var ret bool
if r.allowance < 1.0 {
ret = true
} else {
r.allowance -= 1.0
ret = false
}
if r.allowance < 1.0 {
ret = true
} else {
r.allowance -= 1.0
ret = false
}
return ret
return ret
}
```
Using this package is quite easy:
```
// rate limit at 100/s
nl = ratelimit.NewRateLimiter(100)
@ -139,7 +137,6 @@ Using this package is quite easy:
// .. rate is not exceeded, process as needed
...
}
```
[Anti Huimaa](http://stackoverflow.com/questions/667508/whats-a-good-rate-limiting-algorithm) came up with this simple algorithm.

@ -8,30 +8,30 @@ Streaming the body:
package main
import (
"bytes"
"log"
"net/smtp"
"bytes"
"log"
"net/smtp"
)
func main() {
// Connect to the remote SMTP server.
c, err := smtp.Dial("mail.example.com:25")
if err != nil {
log.Fatal(err)
}
// Set the sender and recipient.
c.Mail("sender@example.org")
c.Rcpt("recipient@example.net")
// Send the email body.
wc, err := c.Data()
if err != nil {
log.Fatal(err)
}
defer wc.Close()
buf := bytes.NewBufferString("This is the email body.")
if _, err = buf.WriteTo(wc); err != nil {
log.Fatal(err)
}
// Connect to the remote SMTP server.
c, err := smtp.Dial("mail.example.com:25")
if err != nil {
log.Fatal(err)
}
// Set the sender and recipient.
c.Mail("sender@example.org")
c.Rcpt("recipient@example.net")
// Send the email body.
wc, err := c.Data()
if err != nil {
log.Fatal(err)
}
defer wc.Close()
buf := bytes.NewBufferString("This is the email body.")
if _, err = buf.WriteTo(wc); err != nil {
log.Fatal(err)
}
}
```

@ -7,22 +7,22 @@ Sometimes an application needs to save internal state or perform some cleanup ac
The following code demonstrates a program that waits for an interrupt signal and removes a temporary file when it occurs.
```
package main
import (
"io/ioutil"
"os"
"os/signal"
)
func main() {
f, err := ioutil.TempFile("", "test")
if err != nil {
panic(err)
}
defer os.Remove(f.Name())
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
<-sig
}
package main
import (
"io/ioutil"
"os"
"os/signal"
)
func main() {
f, err := ioutil.TempFile("", "test")
if err != nil {
panic(err)
}
defer os.Remove(f.Name())
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
<-sig
}
```

@ -31,8 +31,8 @@ a[i], a = a[len(a)-1], a[:len(a)-1]
> ` Cut `
```
copy(a[i:], a[j:])
for k, n := len(a)-j+i, len(a); k < n; k ++ {
a[k] = nil // or the zero value of T
for k, n := len(a)-j+i, len(a); k < n; k++ {
a[k] = nil // or the zero value of T
} // for k
a = a[:len(a)-j+i]
```
@ -89,8 +89,8 @@ This trick uses the fact that a slice shares the same backing array and capacity
```
b := a[:0]
for _, x := range a {
if f(x) {
b = append(b, x)
}
if f(x) {
b = append(b, x)
}
}
```

162
Switch.md

@ -5,20 +5,20 @@ Spec: http://golang.org/doc/go_spec.html#Switch_statements
Go's ` switch ` statements are pretty neat. For one thing, you don't need to break at the end of each case.
```
switch c {
case '&':
esc = "&amp;"
case '\'':
esc = "&apos;"
case '<':
esc = "&lt;"
case '>':
esc = "&gt;"
case '"':
esc = "&quot;"
default:
panic("unrecognized escape character")
}
switch c {
case '&':
esc = "&amp;"
case '\'':
esc = "&apos;"
case '<':
esc = "&lt;"
case '>':
esc = "&gt;"
case '"':
esc = "&quot;"
default:
panic("unrecognized escape character")
}
```
[src/pkg/html/escape.go](http://golang.org/src/pkg/html/escape.go#L178)
@ -28,35 +28,35 @@ Go's ` switch ` statements are pretty neat. For one thing, you don't need to bre
Switches work on values of any type.
```
switch syscall.OS {
case "windows":
sd = &sysDir{
Getenv("SystemRoot") + `\system32\drivers\etc`,
[]string{
"hosts",
"networks",
"protocol",
"services",
},
}
case "plan9":
sd = &sysDir{
"/lib/ndb",
[]string{
"common",
"local",
},
}
default:
sd = &sysDir{
"/etc",
[]string{
"group",
"hosts",
"passwd",
},
}
switch syscall.OS {
case "windows":
sd = &sysDir{
Getenv("SystemRoot") + `\system32\drivers\etc`,
[]string{
"hosts",
"networks",
"protocol",
"services",
},
}
case "plan9":
sd = &sysDir{
"/lib/ndb",
[]string{
"common",
"local",
},
}
default:
sd = &sysDir{
"/etc",
[]string{
"group",
"hosts",
"passwd",
},
}
}
```
## Missing expression
@ -65,15 +65,15 @@ In fact, you don't need to switch on anything at all. A switch with no value mea
```
func unhex(c byte) byte {
switch {
case '0' <= c && c <= '9':
return c - '0'
case 'a' <= c && c <= 'f':
return c - 'a' + 10
case 'A' <= c && c <= 'F':
return c - 'A' + 10
}
return 0
switch {
case '0' <= c && c <= '9':
return c - '0'
case 'a' <= c && c <= 'f':
return c - 'a' + 10
case 'A' <= c && c <= 'F':
return c - 'A' + 10
}
return 0
}
```
@ -86,15 +86,15 @@ command := ReadCommand()
argv := strings.Fields(command)
switch argv[0] {
case "echo":
fmt.Print(argv[1:]...)
fmt.Print(argv[1:]...)
case "cat":
if len(argv) <= 1 {
fmt.Println("Usage: cat <filename>")
break
}
PrintFile(argv[1])
if len(argv) <= 1 {
fmt.Println("Usage: cat <filename>")
break
}
PrintFile(argv[1])
default:
fmt.Println("Unknown command; try 'echo' or 'cat'")
fmt.Println("Unknown command; try 'echo' or 'cat'")
}
```
@ -103,36 +103,36 @@ default:
To fall through to a subsequent case, use the ` fallthrough ` keyword:
```
// Unpack 4 bytes into uint32 to repack into base 85 5-byte.
var v uint32
switch len(src) {
default:
v |= uint32(src[3])
fallthrough
case 3:
v |= uint32(src[2]) << 8
fallthrough
case 2:
v |= uint32(src[1]) << 16
fallthrough
case 1:
v |= uint32(src[0]) << 24
}
// Unpack 4 bytes into uint32 to repack into base 85 5-byte.
var v uint32
switch len(src) {
default:
v |= uint32(src[3])
fallthrough
case 3:
v |= uint32(src[2]) << 8
fallthrough
case 2:
v |= uint32(src[1]) << 16
fallthrough
case 1:
v |= uint32(src[0]) << 24
}
```
[src/pkg/encoding/ascii85/ascii85.go](http://golang.org/src/pkg/encoding/ascii85/ascii85.go#L43)
The 'fallthrough' must be the last thing in the case; you can't write something like
```
switch {
case f():
if g() {
fallthrough // Does not work!
}
h()
default:
error()
switch {
case f():
if g() {
fallthrough // Does not work!
}
h()
default:
error()
}
```
## Multiple cases

@ -91,8 +91,6 @@ func main() {
func init() {
fmt.Print("Starting Up\n")
}
```
@ -102,24 +100,23 @@ Second way is via syscall.NewProc (etc.) instead of syscall.GetProcAddress. The
package main
import (
"syscall"
"unsafe"
"fmt"
"fmt"
"syscall"
"unsafe"
)
func main() {
var mod = syscall.NewLazyDLL("user32.dll")
var proc = mod.NewProc("MessageBoxW");
var MB_YESNOCANCEL = 0x00000003
var mod = syscall.NewLazyDLL("user32.dll")
var proc = mod.NewProc("MessageBoxW")
var MB_YESNOCANCEL = 0x00000003
ret, _, _ := proc.Call(0,
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("Done Title"))),
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("This test is Done."))),
uintptr(MB_YESNOCANCEL))
fmt.Printf("Return: %d\n", ret)
ret, _, _ := proc.Call(0,
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("Done Title"))),
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("This test is Done."))),
uintptr(MB_YESNOCANCEL));
fmt.Printf("Return: %d\n", ret)
}
```
A third way would be to call into libraries basically by "linking" against the library, using the "[cgo](wiki/cgo)" method (this way works in Linux and Windows):
@ -130,7 +127,6 @@ This way would look something like this
import ("C")
...
C.MessageBoxW(...)
```
See [cgo](wiki/cgo) for further details.

2
cgo.md

@ -82,8 +82,8 @@ The following code shows an example of invoking a Go callback from C code. Go pa
package gocallback
import (
"unsafe"
"fmt"
"unsafe"
)
/*