This is a creation in Article, where the information may have evolved or changed.
First, installation
1. Download and decompress
# wget https://storage.googleapis.com/golang/go1.7.1.linux-amd64.tar.gz# tar -C /usr/local -xzf go1.7.1.linux-amd64.tar.gz
2. Add Environment variables
2.1 Add/usr/local/go/bin to the PATH environment variable
Setting variables temporarily in the console
# export GOROOT=/usr/local/go# export PATH=$PATH:$GOROOT/bin
In the configuration file Vim/etc/profile permanent set variables, the specific method asked Baidu.
3. Test environment
# mkdir -p $HOME/go/workspace# export GOPATH=$HOME/go/workspace# mkdir $GOPATH/src/hello# echo "" > $GOPATH/src/hello/hello.go #新增go文件
The contents of the Hello.go inside
package mainimport "fmt"func main() { fmt.Printf("hello, world\n")}
Compiling the project using the Go tool
# go install hello# $GOPATH/bin/hellohello, world
Second, go grammar study
Basic type
Boolstringint int8 int16 int32 int64uint uint8 uint16 uint32 uint64 uintptrbyte//uint8 alias Rune// Int32 alias //Represents a Unicode code float32 float64complex64 complex128
This example shows a variable of different types. As with the import statement, the definition of a variable is "packaged" in a block of syntax.
int
, uint
and the uintptr
type is typically 32 bits on a 32-bit system, and 64 bits on a 64-bit system. When you need to use an integer type, you should prefer int
to use fixed-length integer types or unsigned integer types only for special reasons.
1. Import Package:
1) package Use "" Mark 2) package path/
Import separately
import "fmt"import "math/rand"
Combine import 1, use parentheses to organize package 2, 3, wrap between packages 4,
import ("fmt""math/rand")
2. Famous Guide
Only initial capitalization can be exported
Func Foo(){}Func FOO(){}Func foo(){}
Foo and Foo can be exported, and Foo first letter lowercase cannot be exported.
3. Functions
3.1 Note the type after the variable name.
func(x int, y int ) int { return (x + y);}
3.2 When two or more consecutive function named arguments are of the same type, all but the last type can be omitted
func(x, y, z int ) int { return (x + y + z);}
3.3 can return any number of return values
package mainimport "fmt"func swap(x, y string) (string, string) {return y, x}func main() {a, b := swap("hello", "world")fmt.Println(a, b)}
3.4 Named return value the following code names x, y int
func split(sum int)(x, y int) { x = sum * 4 /9 y = sum - x return}
4 VAR definition variable list
The VAR statement defines a list of variables, just like the argument list of a function, the type is behind.
var c, python, java boolvar (ToBe bool = falseMaxInt uint64 = 1<<64 - 1z complex128 = cmplx.Sqrt(-5 + 12i))
5. Initialize variables
A defined variable can contain an initialization value, and each variable corresponds to a value
var a , b , c string = "hello1","hello2","hello3"
If the value of the initialization variable is an expression, the variable type can be ignored, and the variable type is derived from the expression result
var a , b , c = "hello1","hello2","hello3"
6. Short Declaration variables:=
This usage may not be used outside of the function. In a function, a concise assignment statement can be used to replace Var in a place where the type is clear
a , b , c := "hello11","hello22","hello33"
7, the variable is not explicitly initialized when defined, will default to 0 value .
The value is 0,bool to False,string as "" (empty string)
8. Type Conversion
The expression T (v), which converts the value V to type T, must be cast explicitly.
9. Constants
const Pi = 3.14
10. For loop
10.1for loops do not need to be enclosed in parentheses: initialization statements, loop conditional expressions, post-statements, but loop bodies must be enclosed in {}.
sum := 0; for i := 0; i < 10; i++ { sum += i } fmt.Println(sum)
10.2 For initialization Statements and post statements are optional
sum := 1for ; sum < 1000; { sum += sum}
One for is go while
sum := 1for sum < 1000 { sum += sum}
12 dead Loop
If the loop condition is ignored, the loop does not end, so a more concise statement can be used to express the dead loop
for {}
if
a convenient expression
As with for, the IF statement can execute a simple statement before the condition. The variable scope defined by the statement is only within the If/else range
if v := math.Pow(3,3); v < 20 { fmt.Println(v)} else { fmt.Println(v)}
Easy-to-switch expression
As with for, the switch statement can execute a simple statement before the condition. The variable scope defined by the statement is only within the switch scope
switch os := runtime.GOOS; os {case "darwin":fmt.Println("OS X.")case "linux":fmt.Println("Linux.")default:// freebsd, openbsd,// plan9, windows...fmt.Printf("%s.", os)}
The switch branch does not need a break unless it ends with a fallthrough statement, or the branch automatically terminates
Defer
The defer statement delays the execution of the function until the upper function returns.
1) The parameters of the deferred call are generated immediately, but the function is not called before the upper function returns
2) The deferred function call is pressed into a stack. When the function returns, the deferred function call is called in the order of last in, first out.
func main() { fmt.Println("start") for i := 0 ; i < 10; i++ { fmt.Println(i) } fmt.Println("done")}
#./teststartdone9876543210
16. Pointers
Go has no pointer run character
x, y := 12,13p := &xfmt.Println(*p) #即将打印12p = &y*p = 21fmt.Println(y) #即将打印21
17. Structural struct
1) Statement:
type struName struct{ var1 T1 var2 T2}
2) Call constructor struname{var1,var2 ....}
3) Access mode.成员变量
type Vertex struct { x int y int}func main() { stru := Vertex{1 ,2} fm.Println(stru) #输出:{1,2} fmt.Println(stru.x, stru.y) #输出:1 2 p := &stru fm.Println(*p) #输出:{1,2} fmt.Println(p.x, p.y) #输出:1 2}
18. Arrays
var a [2]stringa[0] = "hello"a[1] = "world"
19, Slice
19.1 a slice will point to a sequential value and contain the length information. Shape: []t
ss := [][]string{ []string{"hello0","world0"}, []string{"hello1","world1"}, []string{"hello2","world2"}, } for i := 0; i< len(ss); i++ { fmt.Println(ss[i][0],ss[i][1]) }
Results
#./testhello0 world0hello1 world1hello2 world2
19.2 pairs of slice slices
Slice can be re-sliced, creating a new slice value that points to the same array. Form: s[lo:hi]
, representing the slice element from lo to hi-1, including the front end, without the back end. s[lo, lo]
is a null value, s[lo,lo+1]
with 1 elements
19.3 Make function
Make: Assigns an array that is all 0 values and returns a slice point to this array. Form: s: = make ([]string, 3)
Note Slice has length and capacity, Length: Len (s), Volume: cap (s)
S: = make ([]string, 0, 5)
Len (s): return 0
Cap (s):: Return 5
19.4 Slice 0 value is nil
Range
The range format for the for loop can iterate over slice or map, and when you use a For loop to traverse a slice, each iteration range returns two values: Subscript and value
var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}func main() {for i, v := range pow {fmt.Printf("2**%d = %d\n", i, v)}}
Output
# ./test2**0 = 12**1 = 22**2 = 42**3 = 82**4 = 162**5 = 322**6 = 642**7 = 128
Shorthand for Range
func main() {pow := make([]int, 10) //只需要索引,去掉", value"for i := range pow {pow[i] = 1 << uint(i)} //只需要治,赋值给_忽略序号for _, value := range pow {fmt.Printf("%d\n", value)}}
map--map values to keys
Map must be created using make before use, otherwise it is an empty map with a value of nil and cannot be assigned a value
var m map[string]intfunc main() { m = make(map[string]int) m["Bell"] = 12 //插入一个元素 fmt.Println("Bell' age is %d", m["Bell"]) //获取一个元素 m["Bell"] = 15 //修改一个元素 m2 := map[string]int { "Alice":13, } elem , ok := m2["Alice"] //使用双赋值检测某个键存在,存在 ok为true,否则为false,并且elem是map元素类型的零值 if ok { fmt.Println("Alice' age is %d", elem) } delete(m2, "Alice") //删除一个元素 elem, ok = m2["Alice"] if ok { fmt.Println("Alice' age is %d", elem) }
22 function values-functions as function arguments or as return values
func compute(fn func(float64, float64) float64) float64 { return fn(float64(3), float64(4)) //调用参数 -fn}func add(x ,y float64) float64 { return x + y}func getfunc() func(float64, float64) float64 { hypot := func(x, y float64) float64 { return math.Sqrt(x*x + y*y) } return hypot //返回函数}func main() { hypot := getfunc() fmt.Println(compute(hypot)) //hypot是参数 fmt.Println(compute(math.Pow)) //math.Pow是参数 fmt.Println(compute(add)) // add 是参数}
23 Function closures
The Go function can be a closed packet.
func adder() func(int) int {sum := 0 //fun 是一个闭包,它引用了函数体之外(本身fn之外)的变量 fn := func(x int) int {sum += xreturn sum}return fn }func main() {pos, neg := adder(), adder() //pos.neg是一个闭包,有各自的绑定的sum变量for i := 0; i < 10; i++ {fmt.Println(pos(i),neg(-2*i),)}}
24 defining a method on a struct type
type Vertex struct { X, Y float64}//方法 Sqrt被 v接收,v出现在 func 关键字和 方法Sqrt名 之间func (v *Vertex) Sqrt() float64 { return math.Sqrt(v.X * v.X + v.Y*v.Y)}func main() { p := &Vertex{3, 4} fmt.Println(p.Sqrt())}
In fact, any type of method can be defined within the warranty, except for the underlying type and other types of packages.
type myfloat float64//如果只读,使用值作为接收者,函数内部是调用者的副本func (f myfloat) Abs() float64 { if f < 0 { return float64(-f) } return float64(f)}//如果是可写,使用指针作为接收者func (f *myfloat) Abs2() float64 { if *f < 0 { *f = -*f return float64(-*f) } return float64(*f)}func main() { fmt.Println((myfloat(-5.5)).Abs() ) f := myfloat(-5.5) (&f).Abs2()}
25 interface
type myfloat float64type Iface interface { Abs() float64}func (f myfloat) Abs() float64 { if f < 0 { return -float64(f) } return float64(f)}func main() { var a Iface f := myfloat(-5.5) a = f; fmt.Println(a.Abs())}
The Web server package HTTP is implemented by HTTP. Handler interface to respond to HTTP requests
type Hello struct{}func (h Hello) ServeHTTP(w http.ResponseWriter,r *http.Request) {fmt.Fprint(w, "Hello!")}func main() {var h Helloerr := http.ListenAndServe("localhost:4000", h)if err != nil {log.Fatal(err)}}
Goroutine
Goroute is a lightweight thread that is managed by the Go runtime environment. Grammar:go f(x, y, x)