mirror of
https://github.com/golang/go.git
synced 2025-05-05 15:43:04 +00:00
Fix formatting after import
parent
87f483adec
commit
0d6986a1f7
5
Books.md
5
Books.md
@ -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,12 +1,14 @@
|
||||
# Bounding resource use
|
||||
|
||||
To bound a program's use of a limited resource, like memory, have goroutines synchronize their use of that resource using a buffered channel (i.e., use the channel as a semaphore):
|
||||
|
||||
```
|
||||
const (
|
||||
AvailableMemory = 10 << 20 // 10 MB
|
||||
AverageMemoryPerRequest = 10 << 10 // 10 KB
|
||||
MaxOutstanding = AvailableMemory / AverageMemoryPerRequest
|
||||
)
|
||||
|
||||
var sem = make(chan int, MaxOutstanding)
|
||||
|
||||
func Serve(queue chan *Request) {
|
||||
|
17
ChromeOS.md
17
ChromeOS.md
@ -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
|
||||
|
||||
@ -58,8 +58,8 @@ import (
|
||||
"hash/adler32"
|
||||
"os"
|
||||
|
||||
"appengine/user"
|
||||
"appengine/foo"
|
||||
"appengine/user"
|
||||
|
||||
"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"
|
||||
. "foo"
|
||||
)
|
||||
```
|
||||
|
||||
@ -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 {
|
||||
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.
|
@ -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) |
|
||||
|
12
Errors.md
12
Errors.md
@ -1,8 +1,8 @@
|
||||
# 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 {
|
||||
@ -21,7 +21,7 @@ if err != nil {
|
||||
|
||||
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:
|
||||
|
||||
@ -35,7 +35,7 @@ func (p ParseError) Error() string {
|
||||
}
|
||||
```
|
||||
|
||||
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) {
|
||||
@ -46,7 +46,7 @@ case ParseError:
|
||||
|
||||
## 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 {
|
||||
type S struct {
|
||||
*bytes.Buffer
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In Go 1.0 the compiler would (incorrectly) accept this struct literal:
|
||||
|
||||
```
|
||||
s := S{
|
||||
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{
|
||||
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() {
|
||||
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() {
|
||||
func fn() {
|
||||
funcVar()
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
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:
|
||||
switch {
|
||||
case false:
|
||||
fallthrough // fall through to 'true' case
|
||||
case true:
|
||||
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:
|
||||
|
1
GoArm.md
1
GoArm.md
@ -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.
|
||||
|
@ -218,7 +218,7 @@ Thus, syntactically speaking, a structure and a pointer to a structure
|
||||
are used in the same way.
|
||||
|
||||
```
|
||||
type myStruct struct { i int }
|
||||
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)
|
||||
@ -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,6 +637,7 @@ 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
|
||||
}
|
||||
@ -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,7 +809,9 @@ 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.
|
||||
```
|
||||
@ -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{} {
|
||||
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 {
|
||||
var dataSlice []int = foo()
|
||||
var interfaceSlice []interface{} = make([]interface{}, len(dataSlice))
|
||||
for i, d := range dataSlice {
|
||||
interfaceSlice[i] = d
|
||||
}
|
||||
}
|
||||
```
|
3
Iota.md
3
Iota.md
@ -18,9 +18,10 @@ Here's one from Effective Go:
|
||||
|
||||
```
|
||||
type ByteSize float64
|
||||
|
||||
const (
|
||||
_ = iota // ignore first value by assigning to blank identifier
|
||||
KB ByteSize = 1<<(10*iota)
|
||||
KB ByteSize = 1 << (10 * iota)
|
||||
MB
|
||||
GB
|
||||
TB
|
||||
|
@ -22,6 +22,7 @@ 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) Append(val int) { *l = append(*l, val) }
|
||||
|
||||
@ -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) 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
|
||||
}
|
||||
|
@ -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
|
||||
|
@ -66,10 +66,10 @@ 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
|
||||
|
||||
@ -79,7 +79,7 @@ type Ratelimiter struct {
|
||||
// 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
|
||||
@ -87,7 +87,7 @@ func NewRateLimiter(rate int) (*Ratelimiter, error) {
|
||||
|
||||
// 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)
|
||||
@ -118,13 +118,11 @@ func (r* Ratelimiter) Limit() bool {
|
||||
|
||||
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.
|
||||
|
@ -7,15 +7,15 @@ 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
|
||||
package main
|
||||
|
||||
import (
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"os/signal"
|
||||
)
|
||||
)
|
||||
|
||||
func main() {
|
||||
func main() {
|
||||
f, err := ioutil.TempFile("", "test")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
@ -24,5 +24,5 @@ The following code demonstrates a program that waits for an interrupt signal and
|
||||
sig := make(chan os.Signal, 1)
|
||||
signal.Notify(sig, os.Interrupt)
|
||||
<-sig
|
||||
}
|
||||
}
|
||||
```
|
@ -31,7 +31,7 @@ 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 ++ {
|
||||
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]
|
||||
|
50
Switch.md
50
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 '&':
|
||||
switch c {
|
||||
case '&':
|
||||
esc = "&"
|
||||
case '\'':
|
||||
case '\'':
|
||||
esc = "'"
|
||||
case '<':
|
||||
case '<':
|
||||
esc = "<"
|
||||
case '>':
|
||||
case '>':
|
||||
esc = ">"
|
||||
case '"':
|
||||
case '"':
|
||||
esc = """
|
||||
default:
|
||||
default:
|
||||
panic("unrecognized escape character")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
[src/pkg/html/escape.go](http://golang.org/src/pkg/html/escape.go#L178)
|
||||
@ -28,8 +28,8 @@ 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":
|
||||
switch syscall.OS {
|
||||
case "windows":
|
||||
sd = &sysDir{
|
||||
Getenv("SystemRoot") + `\system32\drivers\etc`,
|
||||
[]string{
|
||||
@ -39,7 +39,7 @@ Switches work on values of any type.
|
||||
"services",
|
||||
},
|
||||
}
|
||||
case "plan9":
|
||||
case "plan9":
|
||||
sd = &sysDir{
|
||||
"/lib/ndb",
|
||||
[]string{
|
||||
@ -47,7 +47,7 @@ Switches work on values of any type.
|
||||
"local",
|
||||
},
|
||||
}
|
||||
default:
|
||||
default:
|
||||
sd = &sysDir{
|
||||
"/etc",
|
||||
[]string{
|
||||
@ -56,7 +56,7 @@ Switches work on values of any type.
|
||||
"passwd",
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Missing expression
|
||||
@ -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:
|
||||
// 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:
|
||||
case 3:
|
||||
v |= uint32(src[2]) << 8
|
||||
fallthrough
|
||||
case 2:
|
||||
case 2:
|
||||
v |= uint32(src[1]) << 16
|
||||
fallthrough
|
||||
case 1:
|
||||
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():
|
||||
switch {
|
||||
case f():
|
||||
if g() {
|
||||
fallthrough // Does not work!
|
||||
}
|
||||
h()
|
||||
default:
|
||||
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 (
|
||||
"fmt"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var mod = syscall.NewLazyDLL("user32.dll")
|
||||
var proc = mod.NewProc("MessageBoxW");
|
||||
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));
|
||||
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
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"
|
||||
)
|
||||
|
||||
/*
|
||||
|
Loading…
x
Reference in New Issue
Block a user