Go语言精简总结(Part One) - The way to Go

安装

1
2
3
4
5
6
7
8
9
$ apt-get install bison ed gawk libc6-dev mercurial python-setuptools python-dev build-essential
$ hg clone -r release https://go.googlecode.com/hg/ go
$ export GOROOT=$HOME/go
$ export GOARCH=amd64
$ export GOOS=linux
$ export GOTOOL=$HOME/go/pkg/tool/linux_amd64/
$ export PATH=.:$PATH:$GOBIN:$GOTOOL
$ cd go/src
$ ./all.bash

更新go版本

1
2
3
$ cd $GOROOT && hg identify
$ hg pull && hg update release
$ ./all.bash

Workspace 示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
bin/
todo # command executable
pkg/
linux_amd64/
code.google.com/p/goauth2/
oauth.a # package object
github.com/nf/todo/ task.a
src/
code.google.com/p/goauth2/
.hg/ # mercurial repository metadata
oauth/
oauth.go # package source
oauth_test.go # test source
github.com/nf/
todo/
.git/
task/
task.go # package source
todo.go

hello, world

  • 例子1
1
2
3
4
5
package main
import "fmt"
func main() {
fmt.Printf("hello, world\n")
}
1
2
3
$ 6g helloworld.go
$ 6l helloworld.6
$ ./6.out 或者 $ go run helloworld.go
  • 例子2
1
2
3
4
5
6
7
8
9
10
11
12
$HOME/HelloWorldWorkspace/
bin/
helloworld # after go install
pkg/
src/
github.com/msolo/helloworld
.git
helloworld.go
$ export GOPATH=$HOME/HelloWorldWorkspace
$ go install github.com/msolo/helloworld
$ $GOPATH/bin/helloworld

使用自定义包/库

1
2
3
4
5
6
7
8
package main
import (
"fmt"
"github.com/user/newmath"
)
func main() {
fmt.Printf("Hello, world. Sqrt(2) = %v\n", newmath.Sqrt(2))
}
1
2
3
4
5
6
7
8
9
package newmath
// Sqrt returns an approximation to the square root of x.
func Sqrt(x float64) float64 {
z := 1.0
for i := 0; i < 1000; i++ {
z -= (z*z - x) / (2 * z)
}
return z
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$HOME/HelloWorldWorkspace/
bin/
helloworld
pkg/
linux_amd64/ # reflect your OS and architecture
github.com/user/
newmath.a # package object
src/
github.com/user/helloworld
helloworld.go
github.com/user/newmath
sqrt.go
$ go install github.com/user/helloworld