Merge pull request #861 from vCaesar/u19-pr

Optimize typography and  Format and remove en/01.x.md spaces
This commit is contained in:
astaxie
2017-07-01 15:29:44 +08:00
committed by GitHub
14 changed files with 425 additions and 415 deletions

View File

@@ -34,18 +34,18 @@ Execute following commands. ( ***Now author goes back to talk examples*** )
mkdir mymath
Create a new file called `sqrt.go`, type the following content to your file.
```Go
// Source code of $GOPATH/src/mymath/sqrt.go
package mymath
// Source code of $GOPATH/src/mymath/sqrt.go
package mymath
func Sqrt(x float64) float64 {
z := 0.0
for i := 0; i < 1000; i++ {
z -= (z*z - x) / (2 * x)
}
return z
func Sqrt(x float64) float64 {
z := 0.0
for i := 0; i < 1000; i++ {
z -= (z*z - x) / (2 * x)
}
return z
}
```
Now my package directory has been created and it's code has been written. I recommend that you use the same name for your packages as their corresponding directories, and that the directories contain all of the package source files.
## Compile packages
@@ -76,17 +76,17 @@ Write the following content to main.go.
```Go
//$GOPATH/src/mathapp/main.go source code.
package main
import (
"mymath"
"fmt"
)
func main() {
fmt.Printf("Hello, world. Sqrt(2) = %v\n", mymath.Sqrt(2))
}
//$GOPATH/src/mathapp/main.go source code.
package main
import (
"mymath"
"fmt"
)
func main() {
fmt.Printf("Hello, world. Sqrt(2) = %v\n", mymath.Sqrt(2))
}
```
To compile this application, you need to switch to the application directory, which in this case is `$GOPATH/src/mathapp`, then execute the `go install` command. Now you should see an executable file called `mathapp` was generated in the directory `$GOPATH/bin/`. To run this program, use the `./mathapp` command. You should see the following content in your terminal.
@@ -120,7 +120,7 @@ Actually, `go get` clones source code to the $GOPATH/src of the local file syste
You can use remote packages in the same way that we use local packages.
```Go
import "github.com/astaxie/beedb"
import "github.com/astaxie/beedb"
```
## Directory complete structure

View File

@@ -115,12 +115,12 @@ First, download the version of [Sublime](http://www.sublimetext.com/) suitable f
Applicable to Sublime Text 3
```Go
import urllib.request,os;pf='Package Control.sublime-package';ipp=sublime.installed_packages_path();urllib.request.install_opener(urllib.request.build_opener(urllib.request.ProxyHandler()));open(os.path.join(ipp,pf),'wb').write(urllib.request.urlopen('http://sublime.wbond.net/'+pf.replace(' ','%20')).read())
import urllib.request,os;pf='Package Control.sublime-package';ipp=sublime.installed_packages_path();urllib.request.install_opener(urllib.request.build_opener(urllib.request.ProxyHandler()));open(os.path.join(ipp,pf),'wb').write(urllib.request.urlopen('http://sublime.wbond.net/'+pf.replace(' ','%20')).read())
```
Applicable to Sublime Text 2
```Go
import urllib2,os;pf='Package Control.sublime-package';ipp=sublime.installed_packages_path();os.makedirs(ipp)ifnotos.path.exists(ipp)elseNone;urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler()));open(os.path.join(ipp,pf),'wb').write(urllib2.urlopen('http://sublime.wbond.net/'+pf.replace(' ','%20')).read());print('Please restart Sublime Text to finish installation')
import urllib2,os;pf='Package Control.sublime-package';ipp=sublime.installed_packages_path();os.makedirs(ipp)ifnotos.path.exists(ipp)elseNone;urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler()));open(os.path.join(ipp,pf),'wb').write(urllib2.urlopen('http://sublime.wbond.net/'+pf.replace(' ','%20')).read());print('Please restart Sublime Text to finish installation')
```
Restart Sublime Text when the installation has finished. You should then find a `Package Control` option in the "Preferences" menu.

View File

@@ -8,58 +8,58 @@ There are many forms of syntax that can be used to define variables in Go.
The keyword `var` is the basic form to define variables, notice that Go puts the variable type `after` the variable name.
```Go
// define a variable with name “variableName” and type "type"
var variableName type
// define a variable with name “variableName” and type "type"
var variableName type
```
Define multiple variables.
```Go
// define three variables which types are "type"
var vname1, vname2, vname3 type
// define three variables which types are "type"
var vname1, vname2, vname3 type
```
Define a variable with initial value.
```Go
// define a variable with name “variableName”, type "type" and value "value"
var variableName type = value
// define a variable with name “variableName”, type "type" and value "value"
var variableName type = value
```
Define multiple variables with initial values.
```Go
/*
/*
Define three variables with type "type", and initialize their values.
vname1 is v1, vname2 is v2, vname3 is v3
*/
var vname1, vname2, vname3 type = v1, v2, v3
*/
var vname1, vname2, vname3 type = v1, v2, v3
```
Do you think that it's too tedious to define variables use the way above? Don't worry, because the Go team has also found
this to be a problem. Therefore if you want to define variables with initial values, we can just omit the variable type,
so the code will look like this instead:
```Go
/*
/*
Define three variables without type "type", and initialize their values.
vname1 is v1vname2 is v2vname3 is v3
*/
var vname1, vname2, vname3 = v1, v2, v3
*/
var vname1, vname2, vname3 = v1, v2, v3
```
Well, I know this is still not simple enough for you. Let's see how we fix it.
```Go
/*
/*
Define three variables without type "type" and without keyword "var", and initialize their values.
vname1 is v1vname2 is v2vname3 is v3
*/
vname1, vname2, vname3 := v1, v2, v3
*/
vname1, vname2, vname3 := v1, v2, v3
```
Now it looks much better. Use `:=` to replace `var` and `type`, this is called a brief statement. But wait, it has one limitation: this form can only be used inside of functions. You will get compile errors if you try to use it outside of function bodies. Therefore, we usually use `var` to define global variables.
`_` (blank) is a special variable name. Any value that is given to it will be ignored. For example, we give `35` to `b`, and discard `34`.( ***This example just show you how it works. It looks useless here because we often use this symbol when we get function return values.*** )
```Go
_, b := 34, 35
_, b := 34, 35
```
If you don't use variables that you've defined in your program, the compiler will give you compilation errors. Try to compile the following code and see what happens.
```Go
package main
package main
func main() {
var i int
}
func main() {
var i int
}
```
## Constants
@@ -67,16 +67,16 @@ So-called constants are the values that are determined during compile time and y
Define constants as follows.
```Go
const constantName = value
// you can assign type of constants if it's necessary
const Pi float32 = 3.1415926
const constantName = value
// you can assign type of constants if it's necessary
const Pi float32 = 3.1415926
```
More examples.
```Go
const Pi = 3.1415926
const i = 10000
const MaxThread = 10
const prefix = "astaxie_"
const Pi = 3.1415926
const i = 10000
const MaxThread = 10
const prefix = "astaxie_"
```
## Elementary types
@@ -89,9 +89,9 @@ var isActive bool // global variable
var enabled, disabled = true, false // omit type of variables
func test() {
var available bool // local variable
valid := false // brief statement of variable
available = true // assign value to variable
var available bool // local variable
valid := false // brief statement of variable
available = true // assign value to variable
}
```
### Numerical types
@@ -100,11 +100,11 @@ Integer types include both signed and unsigned integer types. Go has `int` and `
One important thing you should know that you cannot assign values between these types, this operation will cause compile errors.
```Go
var a int8
var a int8
var b int32
var b int32
c := a + b
c := a + b
```
Although int32 has a longer length than int8, and has the same type as int, you cannot assign values between them. ( ***c will be asserted as type `int` here*** )
@@ -112,52 +112,52 @@ Float types have the `float32` and `float64` types and no type called `float`. T
That's all? No! Go supports complex numbers as well. `complex128` (with a 64-bit real and 64-bit imaginary part) is the default type, if you need a smaller type, there is one called `complex64` (with a 32-bit real and 32-bit imaginary part). Its form is `RE+IMi`, where `RE` is real part and `IM` is imaginary part, the last `i` is the imaginary number. There is a example of complex number.
```Go
var c complex64 = 5+5i
//output: (5+5i)
fmt.Printf("Value is: %v", c)
var c complex64 = 5+5i
//output: (5+5i)
fmt.Printf("Value is: %v", c)
```
### String
We just talked about how Go uses the UTF-8 character set. Strings are represented by double quotes `""` or backticks ``` `` ```.
```Go
// sample code
var frenchHello string // basic form to define string
var emptyString string = "" // define a string with empty string
func test() {
no, yes, maybe := "no", "yes", "maybe" // brief statement
japaneseHello := "Ohaiou"
frenchHello = "Bonjour" // basic form of assign values
}
// sample code
var frenchHello string // basic form to define string
var emptyString string = "" // define a string with empty string
func test() {
no, yes, maybe := "no", "yes", "maybe" // brief statement
japaneseHello := "Ohaiou"
frenchHello = "Bonjour" // basic form of assign values
}
```
It's impossible to change string values by index. You will get errors when you compile the following code.
```Go
var s string = "hello"
s[0] = 'c'
var s string = "hello"
s[0] = 'c'
```
What if I really want to change just one character in a string? Try the following code.
```Go
s := "hello"
c := []byte(s) // convert string to []byte type
c[0] = 'c'
s2 := string(c) // convert back to string type
fmt.Printf("%s\n", s2)
s := "hello"
c := []byte(s) // convert string to []byte type
c[0] = 'c'
s2 := string(c) // convert back to string type
fmt.Printf("%s\n", s2)
```
You use the `+` operator to combine two strings.
```Go
s := "hello,"
m := " world"
a := s + m
fmt.Printf("%s\n", a)
s := "hello,"
m := " world"
a := s + m
fmt.Printf("%s\n", a)
```
and also.
```Go
s := "hello"
s = "c" + s[1:] // you cannot change string values by index, but you can get values instead.
fmt.Printf("%s\n", s)
s := "hello"
s = "c" + s[1:] // you cannot change string values by index, but you can get values instead.
fmt.Printf("%s\n", s)
```
What if I want to have a multiple-line string?
```Go
m := `hello
m := `hello
world`
```
``` ` ``` will not escape any characters in a string.
@@ -166,10 +166,10 @@ What if I want to have a multiple-line string?
Go has one `error` type for purpose of dealing with error messages. There is also a package called `errors` to handle errors.
```Go
err := errors.New("emit macho dwarf: elf header corrupted")
if err != nil {
fmt.Print(err)
}
err := errors.New("emit macho dwarf: elf header corrupted")
if err != nil {
fmt.Print(err)
}
```
### Underlying data structure
@@ -187,35 +187,35 @@ If you want to define multiple constants, variables or import packages, you can
Basic form.
```Go
import "fmt"
import "os"
import "fmt"
import "os"
const i = 100
const pi = 3.1415
const prefix = "Go_"
const i = 100
const pi = 3.1415
const prefix = "Go_"
var i int
var pi float32
var prefix string
var i int
var pi float32
var prefix string
```
Group form.
```Go
import(
"fmt"
"os"
)
import(
"fmt"
"os"
)
const(
i = 100
pi = 3.1415
prefix = "Go_"
)
const(
i = 100
pi = 3.1415
prefix = "Go_"
)
var(
i int
pi float32
prefix string
)
var(
i int
pi float32
prefix string
)
```
Unless you assign the value of constant is `iota`, the first value of constant in the group `const()` will be `0`. If following constants don't assign values explicitly, their values will be the same as the last one. If the value of last constant is `iota`, the values of following constants which are not assigned are `iota` also.
@@ -223,19 +223,19 @@ Unless you assign the value of constant is `iota`, the first value of constant i
Go has one keyword called `iota`, this keyword is to make `enum`, it begins with `0`, increased by `1`.
```Go
const(
x = iota // x == 0
y = iota // y == 1
z = iota // z == 2
w // If there is no expression after the constants name, it uses the last expression,
//so it's saying w = iota implicitly. Therefore w == 3, and y and z both can omit "= iota" as well.
)
const(
x = iota // x == 0
y = iota // y == 1
z = iota // z == 2
w // If there is no expression after the constants name, it uses the last expression,
//so it's saying w = iota implicitly. Therefore w == 3, and y and z both can omit "= iota" as well.
)
const v = iota // once iota meets keyword `const`, it resets to `0`, so v = 0.
const (
e, f, g = iota, iota, iota // e=0,f=0,g=0 values of iota are same in one line.
)
const v = iota // once iota meets keyword `const`, it resets to `0`, so v = 0.
const (
e, f, g = iota, iota, iota // e=0,f=0,g=0 values of iota are same in one line.
)
```
### Some rules
@@ -250,37 +250,37 @@ The reason that Go is concise because it has some default behaviors.
`array` is an array obviously, we define one as follows.
```Go
var arr [n]type
var arr [n]type
```
in `[n]type`, `n` is the length of the array, `type` is the type of its elements. Like other languages, we use `[]` to get or set element values within arrays.
```Go
var arr [10]int // an array of type [10]int
arr[0] = 42 // array is 0-based
arr[1] = 13 // assign value to element
fmt.Printf("The first element is %d\n", arr[0])
// get element value, it returns 42
fmt.Printf("The last element is %d\n", arr[9])
//it returns default value of 10th element in this array, which is 0 in this case.
var arr [10]int // an array of type [10]int
arr[0] = 42 // array is 0-based
arr[1] = 13 // assign value to element
fmt.Printf("The first element is %d\n", arr[0])
// get element value, it returns 42
fmt.Printf("The last element is %d\n", arr[9])
//it returns default value of 10th element in this array, which is 0 in this case.
```
Because length is a part of the array type, `[3]int` and `[4]int` are different types, so we cannot change the length of arrays. When you use arrays as arguments, functions get their copies instead of references! If you want to use references, you may want to use `slice`. We'll talk about later.
It's possible to use `:=` when you define arrays.
```Go
a := [3]int{1, 2, 3} // define an int array with 3 elements
a := [3]int{1, 2, 3} // define an int array with 3 elements
b := [10]int{1, 2, 3}
// define a int array with 10 elements, of which the first three are assigned.
//The rest of them use the default value 0.
b := [10]int{1, 2, 3}
// define a int array with 10 elements, of which the first three are assigned.
//The rest of them use the default value 0.
c := [...]int{4, 5, 6} // use `…` to replace the length parameter and Go will calculate it for you.
c := [...]int{4, 5, 6} // use `…` to replace the length parameter and Go will calculate it for you.
```
You may want to use arrays as arrays' elements. Let's see how to do this.
```Go
// define a two-dimensional array with 2 elements, and each element has 4 elements.
doubleArray := [2][4]int{[4]int{1, 2, 3, 4}, [4]int{5, 6, 7, 8}}
// define a two-dimensional array with 2 elements, and each element has 4 elements.
doubleArray := [2][4]int{[4]int{1, 2, 3, 4}, [4]int{5, 6, 7, 8}}
// The declaration can be written more concisely as follows.
easyArray := [2][4]int{{1, 2, 3, 4}, {5, 6, 7, 8}}
// The declaration can be written more concisely as follows.
easyArray := [2][4]int{{1, 2, 3, 4}, {5, 6, 7, 8}}
```
Array underlying data structure.
@@ -294,30 +294,30 @@ In many situations, the array type is not a good choice -for instance when we do
`slice` is not really a `dynamic array`. It's a reference type. `slice` points to an underlying `array` whose declaration is similar to `array`, but doesn't need length.
```Go
// just like defining an array, but this time, we exclude the length.
var fslice []int
// just like defining an array, but this time, we exclude the length.
var fslice []int
```
Then we define a `slice`, and initialize its data.
```Go
slice := []byte {'a', 'b', 'c', 'd'}
slice := []byte {'a', 'b', 'c', 'd'}
```
`slice` can redefine existing slices or arrays. `slice` uses `array[i:j]` to slice, where `i` is
the start index and `j` is end index, but notice that `array[j]` will not be sliced since the length
of the slice is `j-i`.
```Go
// define an array with 10 elements whose types are bytes
var ar = [10]byte {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
// define an array with 10 elements whose types are bytes
var ar = [10]byte {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
// define two slices with type []byte
var a, b []byte
// define two slices with type []byte
var a, b []byte
// 'a' points to elements from 3rd to 5th in array ar.
a = ar[2:5]
// now 'a' has elements ar[2],ar[3] and ar[4]
// 'a' points to elements from 3rd to 5th in array ar.
a = ar[2:5]
// now 'a' has elements ar[2],ar[3] and ar[4]
// 'b' is another slice of array ar
b = ar[3:5]
// now 'b' has elements ar[3] and ar[4]
// 'b' is another slice of array ar
b = ar[3:5]
// now 'b' has elements ar[3] and ar[4]
```
Notice the differences between `slice` and `array` when you define them. We use `[]` to let Go
calculate length but use `[]` to define slice only.
@@ -336,22 +336,22 @@ slice has some convenient operations.
More examples pertaining to `slice`
```Go
// define an array
var array = [10]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
// define two slices
var aSlice, bSlice []byte
// define an array
var array = [10]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
// define two slices
var aSlice, bSlice []byte
// some convenient operations
aSlice = array[:3] // equals to aSlice = array[0:3] aSlice has elements a,b,c
aSlice = array[5:] // equals to aSlice = array[5:10] aSlice has elements f,g,h,i,j
aSlice = array[:] // equals to aSlice = array[0:10] aSlice has all elements
// some convenient operations
aSlice = array[:3] // equals to aSlice = array[0:3] aSlice has elements a,b,c
aSlice = array[5:] // equals to aSlice = array[5:10] aSlice has elements f,g,h,i,j
aSlice = array[:] // equals to aSlice = array[0:10] aSlice has all elements
// slice from slice
aSlice = array[3:7] // aSlice has elements d,e,f,glen=4cap=7
bSlice = aSlice[1:3] // bSlice contains aSlice[1], aSlice[2], so it has elements e,f
bSlice = aSlice[:3] // bSlice contains aSlice[0], aSlice[1], aSlice[2], so it has d,e,f
bSlice = aSlice[0:5] // slice could be expanded in range of cap, now bSlice contains d,e,f,g,h
bSlice = aSlice[:] // bSlice has same elements as aSlice does, which are d,e,f,g
// slice from slice
aSlice = array[3:7] // aSlice has elements d,e,f,glen=4cap=7
bSlice = aSlice[1:3] // bSlice contains aSlice[1], aSlice[2], so it has elements e,f
bSlice = aSlice[:3] // bSlice contains aSlice[0], aSlice[1], aSlice[2], so it has d,e,f
bSlice = aSlice[0:5] // slice could be expanded in range of cap, now bSlice contains d,e,f,g,h
bSlice = aSlice[:] // bSlice has same elements as aSlice does, which are d,e,f,g
```
`slice` is a reference type, so any changes will affect other variables pointing to the same slice or array.
For instance, in the case of `aSlice` and `bSlice` above, if you change the value of an element in `aSlice`,
@@ -363,8 +363,8 @@ For instance, in the case of `aSlice` and `bSlice` above, if you change the valu
- The length of `slice`.
- Capacity, the length from start index to end index of `slice`.
```Go
Array_a := [10]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
Slice_a := Array_a[2:5]
Array_a := [10]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
Slice_a := Array_a[2:5]
```
The underlying data structure of the code above as follows.
@@ -391,16 +391,16 @@ Let's see some code. The 'set' and 'get' values in `map` are similar to `slice`,
of type 'int' while `map` can use much more than that: for example `int`, `string`, or whatever you want. Also, they are
all able to use `==` and `!=` to compare values.
```Go
// use string as the key type, int as the value type, and `make` initialize it.
var numbers map[string] int
// another way to define map
numbers := make(map[string]int)
numbers["one"] = 1 // assign value by key
numbers["ten"] = 10
numbers["three"] = 3
// use string as the key type, int as the value type, and `make` initialize it.
var numbers map[string] int
// another way to define map
numbers := make(map[string]int)
numbers["one"] = 1 // assign value by key
numbers["ten"] = 10
numbers["three"] = 3
fmt.Println("The third number is: ", numbers["three"]) // get values
// It prints: The third number is: 3
fmt.Println("The third number is: ", numbers["three"]) // get values
// It prints: The third number is: 3
```
Some notes when you use map.
@@ -413,26 +413,26 @@ You can use form `key:val` to initialize map's values, and `map` has built-in me
Use `delete` to delete an element in `map`.
```Go
// Initialize a map
rating := map[string]float32 {"C":5, "Go":4.5, "Python":4.5, "C++":2 }
// map has two return values. For the second return value, if the key doesn't
//exist'ok' returns false. It returns true otherwise.
csharpRating, ok := rating["C#"]
if ok {
fmt.Println("C# is in the map and its rating is ", csharpRating)
} else {
fmt.Println("We have no rating associated with C# in the map")
}
// Initialize a map
rating := map[string]float32 {"C":5, "Go":4.5, "Python":4.5, "C++":2 }
// map has two return values. For the second return value, if the key doesn't
//exist'ok' returns false. It returns true otherwise.
csharpRating, ok := rating["C#"]
if ok {
fmt.Println("C# is in the map and its rating is ", csharpRating)
} else {
fmt.Println("We have no rating associated with C# in the map")
}
delete(rating, "C") // delete element with key "c"
delete(rating, "C") // delete element with key "c"
```
As I said above, `map` is a reference type. If two `map`s point to same underlying data,
any change will affect both of them.
```Go
m := make(map[string]string)
m["Hello"] = "Bonjour"
m1 := m
m1["Hello"] = "Salut" // now the value of m["hello"] is Salut
m := make(map[string]string)
m["Hello"] = "Bonjour"
m1 := m
m1["Hello"] = "Salut" // now the value of m["hello"] is Salut
```
### make, new
@@ -460,17 +460,17 @@ Figure 2.5 Underlying memory allocation of make and new
Zero-value does not mean empty value. It's the value that variables default to in most cases. Here is a list of some zero-values.
```Go
int 0
int8 0
int32 0
int64 0
uint 0x0
rune 0 // the actual type of rune is int32
byte 0x0 // the actual type of byte is uint8
float32 0 // length is 4 byte
float64 0 //length is 8 byte
bool false
string ""
int 0
int8 0
int32 0
int64 0
uint 0x0
rune 0 // the actual type of rune is int32
byte 0x0 // the actual type of byte is uint8
float32 0 // length is 4 byte
float64 0 //length is 8 byte
bool false
string ""
```
## Links

View File

@@ -12,45 +12,45 @@ The greatest invention in programming is flow control. Because of them, you are
`if` doesn't need parentheses in Go.
```Go
if x > 10 {
fmt.Println("x is greater than 10")
} else {
fmt.Println("x is less than or equal to 10")
}
if x > 10 {
fmt.Println("x is greater than 10")
} else {
fmt.Println("x is less than or equal to 10")
}
```
The most useful thing concerning `if` in Go is that it can have one initialization statement before the conditional statement. The scope of the variables defined in this initialization statement are only available inside the block of the defining `if`.
```Go
// initialize x, then check if x greater than
if x := computedValue(); x > 10 {
fmt.Println("x is greater than 10")
} else {
fmt.Println("x is less than 10")
}
// initialize x, then check if x greater than
if x := computedValue(); x > 10 {
fmt.Println("x is greater than 10")
} else {
fmt.Println("x is less than 10")
}
// the following code will not compile
fmt.Println(x)
// the following code will not compile
fmt.Println(x)
```
Use if-else for multiple conditions.
```Go
if integer == 3 {
fmt.Println("The integer is equal to 3")
} else if integer < 3 {
fmt.Println("The integer is less than 3")
} else {
fmt.Println("The integer is greater than 3")
}
if integer == 3 {
fmt.Println("The integer is equal to 3")
} else if integer < 3 {
fmt.Println("The integer is less than 3")
} else {
fmt.Println("The integer is greater than 3")
}
```
### goto
Go has a `goto` keyword, but be careful when you use it. `goto` reroutes the control flow to a previously defined `label` within the body of same code block.
```Go
func myFunc() {
i := 0
Here: // label ends with ":"
fmt.Println(i)
i++
goto Here // jump to label "Here"
}
func myFunc() {
i := 0
Here: // label ends with ":"
fmt.Println(i)
i++
goto Here // jump to label "Here"
}
```
The label name is case sensitive.
@@ -58,134 +58,135 @@ The label name is case sensitive.
`for` is the most powerful control logic in Go. It can read data in loops and iterative operations, just like `while`.
```Go
for expression1; expression2; expression3 {
//...
}
for expression1; expression2; expression3 {
//...
}
```
`expression1`, `expression2` and `expression3` are all expressions, where `expression1` and `expression3` are variable definitions or return values from functions, and `expression2` is a conditional statement. `expression1` will be executed once before looping, and `expression3` will be executed after each loop.
Examples are more useful than words.
```Go
package main
import "fmt"
package main
func main(){
sum := 0;
for index:=0; index < 10 ; index++ {
sum += index
}
fmt.Println("sum is equal to ", sum)
}
// Printsum is equal to 45
import "fmt"
func main(){
sum := 0;
for index:=0; index < 10 ; index++ {
sum += index
}
fmt.Println("sum is equal to ", sum)
}
// Printsum is equal to 45
```
Sometimes we need multiple assignments, but Go doesn't have the `,` operator, so we use parallel assignment like `i, j = i + 1, j - 1`.
We can omit `expression1` and `expression3` if they are not necessary.
```Go
sum := 1
for ; sum < 1000; {
sum += sum
}
sum := 1
for ; sum < 1000; {
sum += sum
}
```
Omit `;` as well. Feel familiar? Yes, it's identical to `while`.
```Go
sum := 1
for sum < 1000 {
sum += sum
}
sum := 1
for sum < 1000 {
sum += sum
}
```
There are two important operations in loops which are `break` and `continue`. `break` jumps out of the loop, and `continue` skips the current loop and starts the next one. If you have nested loops, use `break` along with labels.
```Go
for index := 10; index>0; index-- {
if index == 5{
break // or continue
}
fmt.Println(index)
}
// break prints 10、9、8、7、6
// continue prints 10、9、8、7、6、4、3、2、1
for index := 10; index>0; index-- {
if index == 5{
break // or continue
}
fmt.Println(index)
}
// break prints 10、9、8、7、6
// continue prints 10、9、8、7、6、4、3、2、1
```
`for` can read data from `array`, `slice`, `map` and `string` when it is used together with `range`.
```Go
for k,v:=range map {
fmt.Println("map's key:",k)
fmt.Println("map's val:",v)
}
for k,v:=range map {
fmt.Println("map's key:",k)
fmt.Println("map's val:",v)
}
```
Because Go supports multi-value returns and gives compile errors when you don't use values that were defined, you may want to use `_` to discard certain return values.
for _, v := range map{
fmt.Println("map's val:", v)
}
```Go
for _, v := range map{
fmt.Println("map's val:", v)
}
```
### switch
Sometimes you may find that you are using too many `if-else` statements to implement some logic, which may make it difficult to read and maintain in the future. This is the perfect time to use the `switch` statement to solve this problem.
```Go
switch sExpr {
case expr1:
some instructions
case expr2:
some other instructions
case expr3:
some other instructions
default:
other code
}
switch sExpr {
case expr1:
some instructions
case expr2:
some other instructions
case expr3:
some other instructions
default:
other code
}
```
The type of `sExpr`, `expr1`, `expr2`, and `expr3` must be the same. `switch` is very flexible. Conditions don't have to be constants and it executes from top to bottom until it matches conditions. If there is no statement after the keyword `switch`, then it matches `true`.
```Go
i := 10
switch i {
case 1:
fmt.Println("i is equal to 1")
case 2, 3, 4:
fmt.Println("i is equal to 2, 3 or 4")
case 10:
fmt.Println("i is equal to 10")
default:
fmt.Println("All I know is that i is an integer")
}
i := 10
switch i {
case 1:
fmt.Println("i is equal to 1")
case 2, 3, 4:
fmt.Println("i is equal to 2, 3 or 4")
case 10:
fmt.Println("i is equal to 10")
default:
fmt.Println("All I know is that i is an integer")
}
```
In the fifth line, we put many values in one `case`, and we don't need to add the `break` keyword at the end of `case`'s body. It will jump out of the switch body once it matched any case. If you want to continue to matching more cases, you need to use the`fallthrough` statement.
```Go
integer := 6
switch integer {
case 4:
fmt.Println("integer <= 4")
fallthrough
case 5:
fmt.Println("integer <= 5")
fallthrough
case 6:
fmt.Println("integer <= 6")
fallthrough
case 7:
fmt.Println("integer <= 7")
fallthrough
case 8:
fmt.Println("integer <= 8")
fallthrough
default:
fmt.Println("default case")
}
integer := 6
switch integer {
case 4:
fmt.Println("integer <= 4")
fallthrough
case 5:
fmt.Println("integer <= 5")
fallthrough
case 6:
fmt.Println("integer <= 6")
fallthrough
case 7:
fmt.Println("integer <= 7")
fallthrough
case 8:
fmt.Println("integer <= 8")
fallthrough
default:
fmt.Println("default case")
}
```
This program prints the following information.
```Go
integer <= 6
integer <= 7
integer <= 8
default case
integer <= 6
integer <= 7
integer <= 8
default case
```
## Functions
Use the `func` keyword to define a function.
```Go
func funcName(input1 type1, input2 type2) (output1 type1, output2 type2) {
// function body
// multi-value return
return value1, value2
}
func funcName(input1 type1, input2 type2) (output1 type1, output2 type2) {
// function body
// multi-value return
return value1, value2
}
```
We can extrapolate the following information from the example above.
@@ -209,9 +210,9 @@ func max(a, b int) int {
return a
}
return b
}
}
func main() {
func main() {
x := 3
y := 4
z := 5
@@ -254,23 +255,23 @@ func main() {
```
The above example returns two values without names -you have the option of naming them also. If we named the return values, we would just need to use `return` to return the values since they are initialized in the function automatically. Notice that if your functions are going to be used outside of the package, which means your function names start with a capital letter, you'd better write complete statements for `return`; it makes your code more readable.
```Go
func SumAndProduct(A, B int) (add int, multiplied int) {
add = A+B
multiplied = A*B
return
}
func SumAndProduct(A, B int) (add int, multiplied int) {
add = A+B
multiplied = A*B
return
}
```
### Variadic functions
Go supports functions with a variable number of arguments. These functions are called "variadic", which means the function allows an uncertain numbers of arguments.
```Go
func myfunc(arg ...int) {}
func myfunc(arg ...int) {}
```
`arg …int` tells Go that this is a function that has variable arguments. Notice that these arguments are type `int`. In the body of function, the `arg` becomes a `slice` of `int`.
```Go
for _, n := range arg {
fmt.Printf("And the number is: %d\n", n)
}
for _, n := range arg {
fmt.Printf("And the number is: %d\n", n)
}
```
### Pass by value and pointers
@@ -372,15 +373,15 @@ func ReadWrite() bool {
```
If there are more than one `defer`s, they will execute by reverse order. The following example will print `4 3 2 1 0`.
```Go
for i := 0; i < 5; i++ {
defer fmt.Printf("%d ", i)
}
for i := 0; i < 5; i++ {
defer fmt.Printf("%d ", i)
}
```
### Functions as values and types
Functions are also variables in Go, we can use `type` to define them. Functions that have the same signature can be seen as the same type.
```Go
type typeName func(input1 inputType1 , input2 inputType2 [, ...]) (result1 resultType1 [, ...])
type typeName func(input1 inputType1 , input2 inputType2 [, ...]) (result1 resultType1 [, ...])
```
What's the advantage of this feature? The answer is that it allows us to pass functions as values.
```Go
@@ -438,25 +439,25 @@ Go doesn't have `try-catch` structure like Java does. Instead of throwing except
The following example shows how to use `panic`.
```Go
var user = os.Getenv("USER")
var user = os.Getenv("USER")
func init() {
if user == "" {
panic("no value for $USER")
}
}
func init() {
if user == "" {
panic("no value for $USER")
}
}
```
The following example shows how to check `panic`.
```Go
func throwsPanic(f func()) (b bool) {
defer func() {
if x := recover(); x != nil {
b = true
}
}()
f() // if f causes panic, it will recover
return
}
func throwsPanic(f func()) (b bool) {
defer func() {
if x := recover(); x != nil {
b = true
}
}()
f() // if f causes panic, it will recover
return
}
```
### `main` function and `init` function
@@ -474,13 +475,13 @@ Figure 2.6 Flow of programs initialization in Go
We use `import` very often in Go programs as follows.
```Go
import(
"fmt"
)
import(
"fmt"
)
```
Then we use functions in that package as follows.
```Go
fmt.Println("hello world")
fmt.Println("hello world")
```
`fmt` is from Go standard library, it is located within $GOROOT/pkg. Go supports third-party packages in two ways.
@@ -494,26 +495,26 @@ There are some special operators when we import packages, and beginners are alwa
1. Dot operator.
Sometime we see people use following way to import packages.
```Go
import(
. "fmt"
)
import(
. "fmt"
)
```
The dot operator means you can omit the package name when you call functions inside of that package. Now `fmt.Printf("Hello world")` becomes to `Printf("Hello world")`.
2. Alias operation.
It changes the name of the package that we imported when we call functions that belong to that package.
```Go
import(
f "fmt"
)
import(
f "fmt"
)
```
Now `fmt.Printf("Hello world")` becomes to `f.Printf("Hello world")`.
3. `_` operator.
This is the operator that is difficult to understand without someone explaining it to you.
```Go
import (
"database/sql"
_ "github.com/ziutek/mymysql/godrv"
)
import (
"database/sql"
_ "github.com/ziutek/mymysql/godrv"
)
```
The `_` operator actually means we just want to import that package and execute its `init` function, and we are not sure if we want to use the functions belonging to that package.

View File

@@ -33,15 +33,15 @@ There are three more ways to define a struct.
- Assign initial values by order
```Go
P := person{"Tom", 25}
P := person{"Tom", 25}
```
- Use the format `field:value` to initialize the struct without order
```Go
P := person{age:24, name:"Bob"}
P := person{age:24, name:"Bob"}
```
- Define an anonymous struct, then initialize it
```Go
P := struct{name string; age int}{"Amy",18}
P := struct{name string; age int}{"Amy",18}
```
Let's see a complete example.
```Go
@@ -141,8 +141,8 @@ Figure 2.7 Embedding in Student and Human
We see that we can access the `age` and `name` fields in Student just like we can in Human. This is how embedded fields work. It's very cool, isn't it? Hold on, there's something cooler! You can even use Student to access Human in this embedded field!
```Go
mark.Human = Human{"Marcus", 55, 220}
mark.Human.age -= 1
mark.Human = Human{"Marcus", 55, 220}
mark.Human.age -= 1
```
All the types in Go can be used as embedded fields.
```Go

View File

@@ -175,13 +175,13 @@ An interface is a set of abstract methods, and can be implemented by non-interfa
An empty interface is an interface that doesn't contain any methods, so all types implement an empty interface. This fact is very useful when we want to store all types at some point, and is similar to void* in C.
```Go
// define a as empty interface
var a interface{}
var i int = 5
s := "Hello world"
// a can store value of any type
a = i
a = s
// define a as empty interface
var a interface{}
var i int = 5
s := "Hello world"
// a can store value of any type
a = i
a = s
```
If a function uses an empty interface as its argument type, it can accept any type; if a function uses empty interface as its return value type, it can return any type.
@@ -223,8 +223,8 @@ func main() {
```
Looking back to the example of Box, you will find that Color implements interface Stringer as well, so we are able to customize the print format. If we don't implement this interface, fmt.Println prints the type with its default format.
```Go
fmt.Println("The biggest one is", boxes.BiggestsColor().String())
fmt.Println("The biggest one is", boxes.BiggestsColor())
fmt.Println("The biggest one is", boxes.BiggestsColor().String())
fmt.Println("The biggest one is", boxes.BiggestsColor())
```
Attention: If the type implemented the interface `error`, fmt will call `Error()`, so you don't have to implement Stringer at this point.
@@ -366,29 +366,29 @@ Reflection in Go is used for determining information at runtime. We use the `ref
There are three steps involved when using reflect. First, we need to convert an interface to reflect types (reflect.Type or reflect.Value, this depends on the situation).
```Go
t := reflect.TypeOf(i) // get meta-data in type i, and use t to get all elements
v := reflect.ValueOf(i) // get actual value in type i, and use v to change its value
t := reflect.TypeOf(i) // get meta-data in type i, and use t to get all elements
v := reflect.ValueOf(i) // get actual value in type i, and use v to change its value
```
After that, we can convert the reflected types to get the values that we need.
```Go
var x float64 = 3.4
v := reflect.ValueOf(x)
fmt.Println("type:", v.Type())
fmt.Println("kind is float64:", v.Kind() == reflect.Float64)
fmt.Println("value:", v.Float())
var x float64 = 3.4
v := reflect.ValueOf(x)
fmt.Println("type:", v.Type())
fmt.Println("kind is float64:", v.Kind() == reflect.Float64)
fmt.Println("value:", v.Float())
```
Finally, if we want to change the values of the reflected types, we need to make it modifiable. As discussed earlier, there is a difference between pass by value and pass by reference. The following code will not compile.
```Go
var x float64 = 3.4
v := reflect.ValueOf(x)
v.SetFloat(7.1)
var x float64 = 3.4
v := reflect.ValueOf(x)
v.SetFloat(7.1)
```
Instead, we must use the following code to change the values from reflect types.
```Go
var x float64 = 3.4
p := reflect.ValueOf(&x)
v := p.Elem()
v.SetFloat(7.1)
var x float64 = 3.4
p := reflect.ValueOf(&x)
v := p.Elem()
v.SetFloat(7.1)
```
We have just discussed the basics of reflection, however you must practice more in order to understand more.

View File

@@ -8,7 +8,7 @@ goroutines and concurrency are built into the core design of Go. They're similar
goroutines run on the thread manager at runtime in Go. We use the `go` keyword to create a new goroutine, which is a function at the underlying level ( ***main() is a goroutine*** ).
```Go
go hello(a, b, c)
go hello(a, b, c)
```
Let's see an example.
```Go
@@ -56,14 +56,14 @@ Before Go 1.5,The scheduler only uses one thread to run all goroutines, which me
goroutines run in the same memory address space, so you have to maintain synchronization when you want to access shared memory. How do you communicate between different goroutines? Go uses a very good communication mechanism called `channel`. `channel` is like a two-way pipeline in Unix shells: use `channel` to send or receive data. The only data type that can be used in channels is the type `channel` and the keyword `chan`. Be aware that you have to use `make` to create a new `channel`.
```Go
ci := make(chan int)
cs := make(chan string)
cf := make(chan interface{})
ci := make(chan int)
cs := make(chan string)
cf := make(chan interface{})
```
channel uses the operator `<-` to send or receive data.
```Go
ch <- v // send v to channel ch.
v := <-ch // receive data from ch, and assign to v
ch <- v // send v to channel ch.
v := <-ch // receive data from ch, and assign to v
```
Let's see more examples.
```Go
@@ -97,10 +97,10 @@ Sending and receiving data in channels blocks by default, so it's much easier to
I introduced non-buffered channels above. Go also has buffered channels that can store more than a single element. For example, `ch := make(chan bool, 4)`, here we create a channel that can store 4 boolean elements. So in this channel, we are able to send 4 elements into it without blocking, but the goroutine will be blocked when you try to send a fifth element and no goroutine receives it.
```Go
ch := make(chan type, n)
ch := make(chan type, n)
n == 0 ! non-bufferblock
n > 0 ! buffernon-block until n elements in the channel
n == 0 ! non-bufferblock
n > 0 ! buffernon-block until n elements in the channel
```
You can try the following code on your computer and change some values.
```Go

View File

@@ -93,7 +93,7 @@
## Sublime Text
这里将介绍Sublime Text 3以下简称Sublime+GoSublime + gocode的组合那么为什么选择这个组合呢
这里将介绍Sublime Text 3以下简称Sublime+ GoSublime + gocode的组合那么为什么选择这个组合呢
- 自动化提示代码,如下图所示
@@ -112,7 +112,7 @@
- Sublime Text 3可免费使用只是保存次数达到一定数量之后就会提示是否购买点击取消继续用和正式注册版本没有任何区别。
接下来就开始讲如何安装,下载[Sublime](http://www.sublimetext.com/)
接下来就开始讲如何安装,下载 [Sublime](http://www.sublimetext.com/)
根据自己相应的系统下载相应的版本然后打开Sublime对于不熟悉Sublime的同学可以先看一下这篇文章[Sublime Text 全程指南](http://blog.jobbole.com/88648/)或者[sublime text3入门教程](http://blog.csdn.net/sam976/article/details/52076271)
@@ -146,7 +146,7 @@ import urllib2,os;pf='Package Control.sublime-package';ipp=sublime.installed_pa
这个时候输入GoSublime按确定就开始安装了。同理应用于SidebarEnhancements和Go Build。
3. 安装[gocode](https://github.com/nsf/gocode/)
3. 安装 [gocode](https://github.com/nsf/gocode/)
go get -u github.com/nsf/gocode
@@ -189,15 +189,15 @@ vscode是微软基于Electron和web技术构建的开源编辑器, 是一款很
2、安装Go插件
点击右边的Extensions图标
点击右边的 Extensions 图标
搜索Go插件
在插件列表中,选择 Go进行安装安装之后系统会提示重启Visual Studio Code。
在插件列表中,选择 Go进行安装安装之后系统会提示重启 Visual Studio Code。
建议把自动保存功能开启。开启方法为选择菜单File点击Auto save。
建议把自动保存功能开启。开启方法为:选择菜单 File点击 Auto save。
vscode代码设置可用于Go扩展。这些都可以在用户的喜好来设置或工作区设置.vscode/settings.json
打开首选项-用户设置settings.json:
打开首选项-用户设置 settings.json:
```Go
@@ -218,7 +218,7 @@ vscode代码设置可用于Go扩展。这些都可以在用户的喜好来设置
}
```
接着安装依赖包支持(网络不稳定,请直接到Github[Golang](https://github.com/golang)下载再移动到相关目录):
接着安装依赖包支持(网络不稳定,请直接到 Github [Golang](https://github.com/golang) 下载再移动到相关目录):
```Go
go get -u -v github.com/nsf/gocode
go get -u -v github.com/rogpeppe/godef
@@ -233,7 +233,7 @@ go get -u -v golang.org/x/tools/cmd/guru
go get -u -v github.com/cweill/gotests/...
```
vscode还有一项很强大的功能就是断点调试,结合[delve](https://github.com/derekparker/delve)可以很好的进行Go代码调试
vscode 还有一项很强大的功能就是断点调试,结合 [delve](https://github.com/derekparker/delve) 可以很好的进行 Go 代码调试
```Go

View File

@@ -39,10 +39,11 @@ CREATE TABLE `userdetail` (
package main
import (
_ "github.com/go-sql-driver/mysql"
"database/sql"
"fmt"
//"time"
_ "github.com/go-sql-driver/mysql"
)
func main() {

View File

@@ -38,6 +38,7 @@ import (
"database/sql"
"fmt"
"time"
_ "github.com/mattn/go-sqlite3"
)

View File

@@ -47,6 +47,7 @@ package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)

View File

@@ -22,11 +22,12 @@ package main
import (
"fmt"
"github.com/garyburd/redigo/redis"
"os"
"os/signal"
"os/signal"
"syscall"
"time"
"github.com/garyburd/redigo/redis"
)
var (
@@ -103,8 +104,9 @@ https://github.com/astaxie/goredis
package main
import (
"github.com/astaxie/goredis"
"fmt"
"github.com/astaxie/goredis"
)
func main() {
@@ -158,9 +160,10 @@ package main
import (
"fmt"
"log"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"log"
)
type Person struct {

View File

@@ -68,9 +68,10 @@ package main
import (
"fmt"
"github.com/julienschmidt/httprouter"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {

View File

@@ -33,8 +33,9 @@ log.WithFields(log.Fields{
package main
import (
log "github.com/Sirupsen/logrus"
"os"
log "github.com/Sirupsen/logrus"
)
func init() {
@@ -122,8 +123,9 @@ package logs
import (
// "errors"
"fmt"
seelog "github.com/cihub/seelog"
// "io"
seelog "github.com/cihub/seelog"
)
var Logger seelog.LoggerInterface