Format and remove en/02.2.md spaces
This commit is contained in:
@@ -115,12 +115,12 @@ First, download the version of [Sublime](http://www.sublimetext.com/) suitable f
|
|||||||
Applicable to Sublime Text 3:
|
Applicable to Sublime Text 3:
|
||||||
|
|
||||||
```Go
|
```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:
|
Applicable to Sublime Text 2:
|
||||||
|
|
||||||
```Go
|
```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.
|
Restart Sublime Text when the installation has finished. You should then find a `Package Control` option in the "Preferences" menu.
|
||||||
|
|||||||
316
en/02.2.md
316
en/02.2.md
@@ -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.
|
The keyword `var` is the basic form to define variables, notice that Go puts the variable type `after` the variable name.
|
||||||
```Go
|
```Go
|
||||||
// define a variable with name “variableName” and type "type"
|
// define a variable with name “variableName” and type "type"
|
||||||
var variableName type
|
var variableName type
|
||||||
```
|
```
|
||||||
Define multiple variables.
|
Define multiple variables.
|
||||||
```Go
|
```Go
|
||||||
// define three variables which types are "type"
|
// define three variables which types are "type"
|
||||||
var vname1, vname2, vname3 type
|
var vname1, vname2, vname3 type
|
||||||
```
|
```
|
||||||
Define a variable with initial value.
|
Define a variable with initial value.
|
||||||
```Go
|
```Go
|
||||||
// define a variable with name “variableName”, type "type" and value "value"
|
// define a variable with name “variableName”, type "type" and value "value"
|
||||||
var variableName type = value
|
var variableName type = value
|
||||||
```
|
```
|
||||||
Define multiple variables with initial values.
|
Define multiple variables with initial values.
|
||||||
```Go
|
```Go
|
||||||
/*
|
/*
|
||||||
Define three variables with type "type", and initialize their values.
|
Define three variables with type "type", and initialize their values.
|
||||||
vname1 is v1, vname2 is v2, vname3 is v3
|
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
|
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,
|
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:
|
so the code will look like this instead:
|
||||||
```Go
|
```Go
|
||||||
/*
|
/*
|
||||||
Define three variables without type "type", and initialize their values.
|
Define three variables without type "type", and initialize their values.
|
||||||
vname1 is v1,vname2 is v2,vname3 is v3
|
vname1 is v1,vname2 is v2,vname3 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.
|
Well, I know this is still not simple enough for you. Let's see how we fix it.
|
||||||
```Go
|
```Go
|
||||||
/*
|
/*
|
||||||
Define three variables without type "type" and without keyword "var", and initialize their values.
|
Define three variables without type "type" and without keyword "var", and initialize their values.
|
||||||
vname1 is v1,vname2 is v2,vname3 is v3
|
vname1 is v1,vname2 is v2,vname3 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.
|
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.*** )
|
`_` (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
|
```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.
|
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
|
```Go
|
||||||
package main
|
package main
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var i int
|
var i int
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
## Constants
|
## Constants
|
||||||
|
|
||||||
@@ -67,16 +67,16 @@ So-called constants are the values that are determined during compile time and y
|
|||||||
|
|
||||||
Define constants as follows.
|
Define constants as follows.
|
||||||
```Go
|
```Go
|
||||||
const constantName = value
|
const constantName = value
|
||||||
// you can assign type of constants if it's necessary
|
// you can assign type of constants if it's necessary
|
||||||
const Pi float32 = 3.1415926
|
const Pi float32 = 3.1415926
|
||||||
```
|
```
|
||||||
More examples.
|
More examples.
|
||||||
```Go
|
```Go
|
||||||
const Pi = 3.1415926
|
const Pi = 3.1415926
|
||||||
const i = 10000
|
const i = 10000
|
||||||
const MaxThread = 10
|
const MaxThread = 10
|
||||||
const prefix = "astaxie_"
|
const prefix = "astaxie_"
|
||||||
```
|
```
|
||||||
## Elementary types
|
## Elementary types
|
||||||
|
|
||||||
@@ -89,9 +89,9 @@ var isActive bool // global variable
|
|||||||
var enabled, disabled = true, false // omit type of variables
|
var enabled, disabled = true, false // omit type of variables
|
||||||
|
|
||||||
func test() {
|
func test() {
|
||||||
var available bool // local variable
|
var available bool // local variable
|
||||||
valid := false // brief statement of variable
|
valid := false // brief statement of variable
|
||||||
available = true // assign value to variable
|
available = true // assign value to variable
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
### Numerical types
|
### 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.
|
One important thing you should know that you cannot assign values between these types, this operation will cause compile errors.
|
||||||
```Go
|
```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*** )
|
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.
|
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
|
```Go
|
||||||
var c complex64 = 5+5i
|
var c complex64 = 5+5i
|
||||||
//output: (5+5i)
|
//output: (5+5i)
|
||||||
fmt.Printf("Value is: %v", c)
|
fmt.Printf("Value is: %v", c)
|
||||||
```
|
```
|
||||||
### String
|
### String
|
||||||
|
|
||||||
We just talked about how Go uses the UTF-8 character set. Strings are represented by double quotes `""` or backticks ``` `` ```.
|
We just talked about how Go uses the UTF-8 character set. Strings are represented by double quotes `""` or backticks ``` `` ```.
|
||||||
```Go
|
```Go
|
||||||
// sample code
|
// sample code
|
||||||
var frenchHello string // basic form to define string
|
var frenchHello string // basic form to define string
|
||||||
var emptyString string = "" // define a string with empty string
|
var emptyString string = "" // define a string with empty string
|
||||||
func test() {
|
func test() {
|
||||||
no, yes, maybe := "no", "yes", "maybe" // brief statement
|
no, yes, maybe := "no", "yes", "maybe" // brief statement
|
||||||
japaneseHello := "Ohaiou"
|
japaneseHello := "Ohaiou"
|
||||||
frenchHello = "Bonjour" // basic form of assign values
|
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.
|
It's impossible to change string values by index. You will get errors when you compile the following code.
|
||||||
```Go
|
```Go
|
||||||
var s string = "hello"
|
var s string = "hello"
|
||||||
s[0] = 'c'
|
s[0] = 'c'
|
||||||
```
|
```
|
||||||
What if I really want to change just one character in a string? Try the following code.
|
What if I really want to change just one character in a string? Try the following code.
|
||||||
```Go
|
```Go
|
||||||
s := "hello"
|
s := "hello"
|
||||||
c := []byte(s) // convert string to []byte type
|
c := []byte(s) // convert string to []byte type
|
||||||
c[0] = 'c'
|
c[0] = 'c'
|
||||||
s2 := string(c) // convert back to string type
|
s2 := string(c) // convert back to string type
|
||||||
fmt.Printf("%s\n", s2)
|
fmt.Printf("%s\n", s2)
|
||||||
```
|
```
|
||||||
You use the `+` operator to combine two strings.
|
You use the `+` operator to combine two strings.
|
||||||
```Go
|
```Go
|
||||||
s := "hello,"
|
s := "hello,"
|
||||||
m := " world"
|
m := " world"
|
||||||
a := s + m
|
a := s + m
|
||||||
fmt.Printf("%s\n", a)
|
fmt.Printf("%s\n", a)
|
||||||
```
|
```
|
||||||
and also.
|
and also.
|
||||||
```Go
|
```Go
|
||||||
s := "hello"
|
s := "hello"
|
||||||
s = "c" + s[1:] // you cannot change string values by index, but you can get values instead.
|
s = "c" + s[1:] // you cannot change string values by index, but you can get values instead.
|
||||||
fmt.Printf("%s\n", s)
|
fmt.Printf("%s\n", s)
|
||||||
```
|
```
|
||||||
What if I want to have a multiple-line string?
|
What if I want to have a multiple-line string?
|
||||||
```Go
|
```Go
|
||||||
m := `hello
|
m := `hello
|
||||||
world`
|
world`
|
||||||
```
|
```
|
||||||
``` ` ``` will not escape any characters in a string.
|
``` ` ``` 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 has one `error` type for purpose of dealing with error messages. There is also a package called `errors` to handle errors.
|
||||||
```Go
|
```Go
|
||||||
err := errors.New("emit macho dwarf: elf header corrupted")
|
err := errors.New("emit macho dwarf: elf header corrupted")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Print(err)
|
fmt.Print(err)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
### Underlying data structure
|
### Underlying data structure
|
||||||
|
|
||||||
@@ -187,35 +187,35 @@ If you want to define multiple constants, variables or import packages, you can
|
|||||||
|
|
||||||
Basic form.
|
Basic form.
|
||||||
```Go
|
```Go
|
||||||
import "fmt"
|
import "fmt"
|
||||||
import "os"
|
import "os"
|
||||||
|
|
||||||
const i = 100
|
const i = 100
|
||||||
const pi = 3.1415
|
const pi = 3.1415
|
||||||
const prefix = "Go_"
|
const prefix = "Go_"
|
||||||
|
|
||||||
var i int
|
var i int
|
||||||
var pi float32
|
var pi float32
|
||||||
var prefix string
|
var prefix string
|
||||||
```
|
```
|
||||||
Group form.
|
Group form.
|
||||||
```Go
|
```Go
|
||||||
import(
|
import(
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
const(
|
const(
|
||||||
i = 100
|
i = 100
|
||||||
pi = 3.1415
|
pi = 3.1415
|
||||||
prefix = "Go_"
|
prefix = "Go_"
|
||||||
)
|
)
|
||||||
|
|
||||||
var(
|
var(
|
||||||
i int
|
i int
|
||||||
pi float32
|
pi float32
|
||||||
prefix string
|
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.
|
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 has one keyword called `iota`, this keyword is to make `enum`, it begins with `0`, increased by `1`.
|
||||||
```Go
|
```Go
|
||||||
const(
|
const(
|
||||||
x = iota // x == 0
|
x = iota // x == 0
|
||||||
y = iota // y == 1
|
y = iota // y == 1
|
||||||
z = iota // z == 2
|
z = iota // z == 2
|
||||||
w // If there is no expression after the constants name, it uses the last expression,
|
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.
|
//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 v = iota // once iota meets keyword `const`, it resets to `0`, so v = 0.
|
||||||
|
|
||||||
const (
|
const (
|
||||||
e, f, g = iota, iota, iota // e=0,f=0,g=0 values of iota are same in one line.
|
e, f, g = iota, iota, iota // e=0,f=0,g=0 values of iota are same in one line.
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
### Some rules
|
### 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.
|
`array` is an array obviously, we define one as follows.
|
||||||
```Go
|
```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.
|
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
|
```Go
|
||||||
var arr [10]int // an array of type [10]int
|
var arr [10]int // an array of type [10]int
|
||||||
arr[0] = 42 // array is 0-based
|
arr[0] = 42 // array is 0-based
|
||||||
arr[1] = 13 // assign value to element
|
arr[1] = 13 // assign value to element
|
||||||
fmt.Printf("The first element is %d\n", arr[0])
|
fmt.Printf("The first element is %d\n", arr[0])
|
||||||
// get element value, it returns 42
|
// get element value, it returns 42
|
||||||
fmt.Printf("The last element is %d\n", arr[9])
|
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.
|
//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.
|
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.
|
It's possible to use `:=` when you define arrays.
|
||||||
```Go
|
```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}
|
b := [10]int{1, 2, 3}
|
||||||
// define a int array with 10 elements, of which the first three are assigned.
|
// define a int array with 10 elements, of which the first three are assigned.
|
||||||
//The rest of them use the default value 0.
|
//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.
|
You may want to use arrays as arrays' elements. Let's see how to do this.
|
||||||
```Go
|
```Go
|
||||||
// define a two-dimensional array with 2 elements, and each element has 4 elements.
|
// 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}}
|
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.
|
// The declaration can be written more concisely as follows.
|
||||||
easyArray := [2][4]int{{1, 2, 3, 4}, {5, 6, 7, 8}}
|
easyArray := [2][4]int{{1, 2, 3, 4}, {5, 6, 7, 8}}
|
||||||
```
|
```
|
||||||
Array underlying data structure.
|
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.
|
`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
|
```Go
|
||||||
// just like defining an array, but this time, we exclude the length.
|
// just like defining an array, but this time, we exclude the length.
|
||||||
var fslice []int
|
var fslice []int
|
||||||
```
|
```
|
||||||
Then we define a `slice`, and initialize its data.
|
Then we define a `slice`, and initialize its data.
|
||||||
```Go
|
```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
|
`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
|
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`.
|
of the slice is `j-i`.
|
||||||
```Go
|
```Go
|
||||||
// define an array with 10 elements whose types are bytes
|
// define an array with 10 elements whose types are bytes
|
||||||
var ar = [10]byte {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
|
var ar = [10]byte {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
|
||||||
|
|
||||||
// define two slices with type []byte
|
// define two slices with type []byte
|
||||||
var a, b []byte
|
var a, b []byte
|
||||||
|
|
||||||
// 'a' points to elements from 3rd to 5th in array ar.
|
// 'a' points to elements from 3rd to 5th in array ar.
|
||||||
a = ar[2:5]
|
a = ar[2:5]
|
||||||
// now 'a' has elements ar[2],ar[3] and ar[4]
|
// now 'a' has elements ar[2],ar[3] and ar[4]
|
||||||
|
|
||||||
// 'b' is another slice of array ar
|
// 'b' is another slice of array ar
|
||||||
b = ar[3:5]
|
b = ar[3:5]
|
||||||
// now 'b' has elements ar[3] and ar[4]
|
// 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
|
Notice the differences between `slice` and `array` when you define them. We use `[…]` to let Go
|
||||||
calculate length but use `[]` to define slice only.
|
calculate length but use `[]` to define slice only.
|
||||||
@@ -336,22 +336,22 @@ slice has some convenient operations.
|
|||||||
|
|
||||||
More examples pertaining to `slice`
|
More examples pertaining to `slice`
|
||||||
```Go
|
```Go
|
||||||
// define an array
|
// define an array
|
||||||
var array = [10]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
|
var array = [10]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
|
||||||
// define two slices
|
// define two slices
|
||||||
var aSlice, bSlice []byte
|
var aSlice, bSlice []byte
|
||||||
|
|
||||||
// some convenient operations
|
// some convenient operations
|
||||||
aSlice = array[:3] // equals to aSlice = array[0:3] aSlice has elements a,b,c
|
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[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
|
aSlice = array[:] // equals to aSlice = array[0:10] aSlice has all elements
|
||||||
|
|
||||||
// slice from slice
|
// slice from slice
|
||||||
aSlice = array[3:7] // aSlice has elements d,e,f,g,len=4,cap=7
|
aSlice = array[3:7] // aSlice has elements d,e,f,g,len=4,cap=7
|
||||||
bSlice = aSlice[1:3] // bSlice contains aSlice[1], aSlice[2], so it has elements e,f
|
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[: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[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
|
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.
|
`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`,
|
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`.
|
- The length of `slice`.
|
||||||
- Capacity, the length from start index to end index of `slice`.
|
- Capacity, the length from start index to end index of `slice`.
|
||||||
```Go
|
```Go
|
||||||
Array_a := [10]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
|
Array_a := [10]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}
|
||||||
Slice_a := Array_a[2:5]
|
Slice_a := Array_a[2:5]
|
||||||
```
|
```
|
||||||
The underlying data structure of the code above as follows.
|
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
|
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.
|
all able to use `==` and `!=` to compare values.
|
||||||
```Go
|
```Go
|
||||||
// use string as the key type, int as the value type, and `make` initialize it.
|
// use string as the key type, int as the value type, and `make` initialize it.
|
||||||
var numbers map[string] int
|
var numbers map[string] int
|
||||||
// another way to define map
|
// another way to define map
|
||||||
numbers := make(map[string]int)
|
numbers := make(map[string]int)
|
||||||
numbers["one"] = 1 // assign value by key
|
numbers["one"] = 1 // assign value by key
|
||||||
numbers["ten"] = 10
|
numbers["ten"] = 10
|
||||||
numbers["three"] = 3
|
numbers["three"] = 3
|
||||||
|
|
||||||
fmt.Println("The third number is: ", numbers["three"]) // get values
|
fmt.Println("The third number is: ", numbers["three"]) // get values
|
||||||
// It prints: The third number is: 3
|
// It prints: The third number is: 3
|
||||||
```
|
```
|
||||||
Some notes when you use map.
|
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`.
|
Use `delete` to delete an element in `map`.
|
||||||
```Go
|
```Go
|
||||||
// Initialize a map
|
// Initialize a map
|
||||||
rating := map[string]float32 {"C":5, "Go":4.5, "Python":4.5, "C++":2 }
|
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
|
// map has two return values. For the second return value, if the key doesn't
|
||||||
//exist,'ok' returns false. It returns true otherwise.
|
//exist,'ok' returns false. It returns true otherwise.
|
||||||
csharpRating, ok := rating["C#"]
|
csharpRating, ok := rating["C#"]
|
||||||
if ok {
|
if ok {
|
||||||
fmt.Println("C# is in the map and its rating is ", csharpRating)
|
fmt.Println("C# is in the map and its rating is ", csharpRating)
|
||||||
} else {
|
} else {
|
||||||
fmt.Println("We have no rating associated with C# in the map")
|
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,
|
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.
|
any change will affect both of them.
|
||||||
```Go
|
```Go
|
||||||
m := make(map[string]string)
|
m := make(map[string]string)
|
||||||
m["Hello"] = "Bonjour"
|
m["Hello"] = "Bonjour"
|
||||||
m1 := m
|
m1 := m
|
||||||
m1["Hello"] = "Salut" // now the value of m["hello"] is Salut
|
m1["Hello"] = "Salut" // now the value of m["hello"] is Salut
|
||||||
```
|
```
|
||||||
### make, new
|
### 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.
|
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
|
```Go
|
||||||
int 0
|
int 0
|
||||||
int8 0
|
int8 0
|
||||||
int32 0
|
int32 0
|
||||||
int64 0
|
int64 0
|
||||||
uint 0x0
|
uint 0x0
|
||||||
rune 0 // the actual type of rune is int32
|
rune 0 // the actual type of rune is int32
|
||||||
byte 0x0 // the actual type of byte is uint8
|
byte 0x0 // the actual type of byte is uint8
|
||||||
float32 0 // length is 4 byte
|
float32 0 // length is 4 byte
|
||||||
float64 0 //length is 8 byte
|
float64 0 //length is 8 byte
|
||||||
bool false
|
bool false
|
||||||
string ""
|
string ""
|
||||||
```
|
```
|
||||||
## Links
|
## Links
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user