以下资源都来自A Tour of Go。可以进行一些简单的交互式的在线编程。
1 欢迎
1.1 hello,世界
hello.go
package main
import "fmt"
func main() {
fmt.Println("Hello, 世界")
}
1.2 sandbox.go
sandbox.go
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Welcome to the playground!")
fmt.Println("The time is", time.Now())
}
2 包、变量和函数
2.1 包 (package)
Every Go program is made up of packages.
Programs start running in package main.
This program is using the packages with import paths “fmt” and “math/rand”.
By convention, the package name is the same as the last element of the import path. For instance, the “math/rand” package comprises files that begin with the statement package rand.
Note: The environment in which these programs are executed is deterministic, so each time you run the example program rand.Intn will return the same number. (To see a different number, seed the number generator; see rand.Seed. Time is constant in the playground, so you will need to use something else as the seed.)
rand.go
package main
import (
"fmt"
"math/rand"
)
func main() {
fmt.Println("My favorite number is", rand.Intn(10))
}
2.2 导入 imports
This code groups the imports into a parenthesized, “factored” import statement.
You can also write multiple import statements, like:
import "fmt"
import "math"
But it is good style to use the factored import statement.
imports.go
package main
import (
"fmt"
"math"
)
func main() {
fmt.Printf("Now you have %g problems.\n", math.Sqrt(7))
}
2.3 导出的名称 exported names
In Go, a name is exported if it begins with a capital letter.
在go语言中,导出的名称以大写字母开头。
For example, Pizza is an exported name, as is Pi, which is exported from the math package.
pizza and pi do not start with a capital letter, so they are not exported.
When importing a package, you can refer only to its exported names. Any “unexported” names are not accessible from outside the package.
Run the code. Notice the error message.
To fix the error, rename math.pi to math.Pi and try it again.
exported_name.go
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.pi)
}
2.4 函数 functions
A function can take zero or more arguments.
In this example, add takes two parameters of type int.
Notice that the type comes after the variable name
(For more about why types look the way they do, see the article on Go’s declaration syntax.)
function.go
package main
import "fmt"
func add(x int, y int) int {
return x + y
}
func main() {
fmt.Println(add(42, 13))
}
2.5 再探函数 functions continue
When two or more consecutive named function parameters share a type, you can omit the type from all but the last.
当有两个或多个连续的函数参数是相同的数据类型时,可以只再最后一个参数后写明类型。
In this example, we shortened
x int, y int
to
x, y int
function.go
package main
import "fmt"
func add(x, y int) int {
return x + y
}
func main() {
fmt.Println(add(42, 13))
}
2.6 多样化的结果 multiple results
A function can return any number of results.
函数可以返回任意数量的结果。
The swap function returns two strings.
multiple_results.go
package main
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("hello", "world")
fmt.Println(a, b)
}
2.7 命名的返回值 named return values
Go’s return values may be named. If so, they are treated as variables defined at the top of the function.
go语言的返回值可以命名,如果这样它们被视为变量,定义在函数首部。
These names should be used to document the meaning of the return values.
A return statement without arguments returns the named return values. This is known as a “naked” return.
Naked return statements should be used only in short functions, as with the example shown here. They can harm readability in longer functions.
named-results.go
package main
import "fmt"
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return
}
func main() {
fmt.Println(split(17))
}
上面代码的结果是:7 10
原因是返回值是命名了的x和y。 所以return的时候,直接返回。
2.8 变量 variables
The var statement declares a list of variables; as in function argument lists, the type is last.
var声明一系列的变量,像函数参数一样,类型放在最后面。
A var statement can be at package or function level. We see both in this example.
variables.go
package main
import "fmt"
var c, python, java bool
func main() {
var i int
fmt.Println(i, c, python, java)
}
2.9 带初始化的变量 variables with initializers
A var declaration can include initializers, one per variable.
If an initializer is present, the type can be omitted; the variable will take the type of the initializer.
variables_with_initializers.go
package main
import "fmt"
var i, j int = 1, 2
func main() {
var c, python, java = true, false, "no!"
fmt.Println(i, j, c, python, java)
}
2.10 短变量定义 short variable declarations
Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.
函数内, := 短赋值语句可以用于代替var declaration
Outside a function, every statement begins with a keyword (var, func, and so on) and so the := construct is not available.
package main
import "fmt"
func main() {
var i, j int = 1, 2
k := 3
c, python, java := true, false, "no!"
fmt.Println(i, j, k, c, python, java)
}
基本数据类型 basic types
Go’s basic types are:
bool
string
int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64 uintptr
byte // alias for uint8
rune // alias for int32
// represents a Unicode code point
float32 float64
complex64 complex128
The example shows variables of several types, and also that variable declarations may be “factored” into blocks, as with import statements.
The int, uint, and uintptr types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems.
When you need an integer value you should use int unless you have a specific reason to use a sized or unsigned integer type.
basic_types.go
package main
import (
"fmt"
"math/cmplx"
)
var (
ToBe bool = false
MaxInt uint64 = 1<<64 - 1
z complex128 = cmplx.Sqrt(-5 + 12i)
)
func main() {
fmt.Printf("Type: %T Value: %v\n", ToBe, ToBe)
fmt.Printf("Type: %T Value: %v\n", MaxInt, MaxInt)
fmt.Printf("Type: %T Value: %v\n", z, z)
}
2.12 默认值 zero values
Variables declared without an explicit initial value are given their zero value.
The zero value is:
0 for numeric types,
false for the boolean type, and
“” (the empty string) for strings.
package main
import "fmt"
func main() {
var i int
var f float64
var b bool
var s string
fmt.Printf("%v %v %v %q\n", i, f, b, s)
}
answer:0 0 false “”
2.13 类型转换
The expression T(v) converts the value v to the type T.
Some numeric conversions:
var i int = 42
var f float64 = float64(i)
var u uint = uint(f)
Or, put more simply:
i := 42
f := float64(i)
u := uint(f)
Unlike in C, in Go assignment between items of different type requires an explicit conversion.
与c语言不同,go语言中不通类型的赋值需要明确的类型转换。
Try removing the float64 or uint conversions in the example and see what happens.
2.14 类型推断 type inference
When declaring a variable without specifying an explicit type (either by using the := syntax or var = expression syntax), the variable’s type is inferred from the value on the right hand side.
When the right hand side of the declaration is typed, the new variable is of that same type:
var i int
j := i // j is an int
But when the right hand side contains an untyped numeric constant, the new variable may be an int, float64, or complex128 depending on the precision of the constant:
i := 42 // int
f := 3.142 // float64
g := 0.867 + 0.5i // complex128
Try changing the initial value of v in the example code and observe how its type is affected.
package main
import "fmt"
func main() {
v := "hello" // change me!
fmt.Printf("v is of type %T\n", v)
}
2.15 常量
Constants are declared like variables, but with the const keyword.
Constants can be character, string, boolean, or numeric values.
Constants cannot be declared using the := syntax.
package main
import "fmt"
const Pi = 3.14
func main() {
const World = "世界"
fmt.Println("Hello", World)
fmt.Println("Happy", Pi, "Day")
const Truth = true
fmt.Println("Go rules?", Truth)
}
2.16 数字常量
Numeric constants are high-precision values.
An untyped constant takes the type needed by its context.
Try printing needInt(Big) too.
(An int can store at maximum a 64-bit integer, and sometimes less.)
package main
import "fmt"
const (
// Create a huge number by shifting a 1 bit left 100 places.
// In other words, the binary number that is 1 followed by 100 zeroes.
Big = 1 << 100
// Shift it right again 99 places, so we end up with 1<<1, or 2.
Small = Big >> 99
)
func needInt(x int) int { return x*10 + 1 }
func needFloat(x float64) float64 {
return x * 0.1
}
func main() {
fmt.Println(needInt(Small))
fmt.Println(needFloat(Small))
fmt.Println(needFloat(Big))
}
answer:
21
0.2
1.2676506002282295e+29
3 流控制:for,if,else,switch 和 defer
3.1 for语句
Go has only one looping construct, the for loop.
go只有一种循环结构,for循环
The basic for loop has three components separated by semicolons:
基本的go语句有三个成分,被分号分开:初始化声明;条件表达式;结束声明
the init statement: executed before the first iteration
the condition expression: evaluated before every iteration
the post statement: executed at the end of every iteration
The init statement will often be a short variable declaration, and the variables declared there are visible only in the scope of the for statement.
The loop will stop iterating once the boolean condition evaluates to false.
Note: Unlike other languages like C, Java, or JavaScript there are no parentheses surrounding the three components of the for statement and the braces { } are always required.
package main
import "fmt"
func main() {
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
fmt.Println(sum)
}
3.2 for continue
The init and post statements are optional.
package main
import "fmt"
func main() {
sum := 1
for ; sum < 1000; {
sum += sum
}
fmt.Println(sum)
}
3.3 for就是go的while语句 For is Go’s “while”
package main
import "fmt"
func main() {
sum := 1
for sum < 1000 {
sum += sum
}
fmt.Println(sum)
}
3.4 无限循环 forever
如果你省略循环条件,循环会无限进行
package main
func main() {
for {
}
}
3.5 if语句
Go’s if statements are like its for loops; the expression need not be surrounded by parentheses ( ) but the braces { } are required.
if.go
package main
import (
"fmt"
"math"
)
func sqrt(x float64) string {
if x < 0 {
return sqrt(-x) + "i"
}
return fmt.Sprint(math.Sqrt(x))
}
func main() {
fmt.Println(sqrt(2), sqrt(-4))
}
3.6 if with a short statement
像for语句一样,if语句在之行条件判断前也可以执行一个短的声明。此处声明的变量的作用域只有if语句内。
if-with-a-short-statement.to
package main
import (
"fmt"
"math"
)
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
}
return lim
}
func main() {
fmt.Println(
pow(3, 2, 10),
pow(3, 3, 20),
)
}
3.7 if and else
Variables declared inside an if short statement are also available inside any of the else blocks.
if-and-else.go
package main
import (
"fmt"
"math"
)
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
} else {
fmt.Printf("%g >= %g\n", v, lim)
}
// can't use v here, though
return lim
}
func main() {
fmt.Println(
pow(3, 2, 10),
pow(3, 3, 20),
)
}
3.8 练习1 循环和函数
Exercise: Loops and Functions
As a way to play with functions and loops, let’s implement a square root function: given a number x, we want to find the number z for which z² is most nearly x.
Computers typically compute the square root of x using a loop. Starting with some guess z, we can adjust z based on how close z² is to x, producing a better guess:
z -= (z*z - x) / (2*z)
Repeating this adjustment makes the guess better and better until we reach an answer that is as close to the actual square root as can be.
Implement this in the func Sqrt provided. A decent starting guess for z is 1, no matter what the input. To begin with, repeat the calculation 10 times and print each z along the way. See how close you get to the answer for various values of x (1, 2, 3, …) and how quickly the guess improves.
Hint: To declare and initialize a floating point value, give it floating point syntax or use a conversion:
z := 1.0
z := float64(1)
Next, change the loop condition to stop once the value has stopped changing (or only changes by a very small amount). See if that’s more or fewer than 10 iterations. Try other initial guesses for z, like x, or x/2. How close are your function’s results to the math.Sqrt in the standard library?
(Note: If you are interested in the details of the algorithm, the z² − x above is how far away z² is from where it needs to be (x), and the division by 2z is the derivative of z², to scale how much we adjust z by how quickly z² is changing. This general approach is called Newton’s method. It works well for many functions but especially well for square root.)
package main
import (
"fmt"
)
func Sqrt(x float64) float64 {
z := 1.0
for i := 0; i < 10; i++ {
z -= (z*z -x) / (2*z)
fmt.Println(z)
}
return z
}
func main() {
fmt.Println(Sqrt(2))
}
3.9 switch语句
A switch statement is a shorter way to write a sequence of if - else statements. It runs the first case whose value is equal to the condition expression.
go语言运行第一个匹配的条件表达式后面的语句。
Go’s switch is like the one in C, C++, Java, JavaScript, and PHP, except that Go only runs the selected case, not all the cases that follow. In effect, the break statement that is needed at the end of each case in those languages is provided automatically in Go. Another important difference is that Go’s switch cases need not be constants, and the values involved need not be integers.
go的每一个分支后都有默然的break, 且判断条件可以不是整数。
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Print("Go runs on ")
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)
}
}
3.10 switch evaluation order
Switch cases evaluate cases from top to bottom, stopping when a case succeeds.
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("When's Saturday?")
today := time.Now().Weekday()
switch time.Saturday {
case today + 0:
fmt.Println("Today.")
case today + 1:
fmt.Println("Tomorrow.")
case today + 2:
fmt.Println("In two days.")
default:
fmt.Println("Too far away.")
}
}
3.11 Switch with no condition
Switch without a condition is the same as switch true.
This construct can be a clean way to write long if-then-else chains.
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("Good morning!")
case t.Hour() < 17:
fmt.Println("Good afternoon.")
default:
fmt.Println("Good evening.")
}
}
3.12 defer
A defer statement defers the execution of a function until the surrounding function returns.
The deferred call’s arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
package main
import "fmt"
func main() {
defer fmt.Println("world")
fmt.Println("hello")
}
3.13 stacking defers
Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order.
To learn more about defer statements read this blog post.
package main
import "fmt"
func main() {
fmt.Println("counting")
for i := 0; i < 10; i++ {
defer fmt.Println(i)
}
fmt.Println("done")
}
结果是:
counting
done
9
8
7
6
5
4
3
2
1
0
4 更多的类型:结构,切片和图
4.1 指针 pointers
**指针的定义:**a pointer holds the memory address of a value.
The type *T
is a pointer to a T
value. Its zero value is nil
.
var p *int
The &
operator generates a pointer to its operand.
i := 42
p = &i
The *
operator denotes the pointer’s underlying value.
fmt.Println(*p) // read i through the pointer p
*p = 21 // set i through the pointer p
This is known as “dereferencing” or “indirecting”.
Unlike C, Go has no pointer arithmetic.
与c语言不同,go语言不支持指针的运算。
package main
import "fmt"
func main() {
i, j := 42, 2701
p := &i // point to i
fmt.Println(*p) // read i through the pointer
*p = 21 // set i through the pointer
fmt.Println(i) // see the new value of i
p = &j // point to j
*p = *p / 37 // divide j through the pointer
fmt.Println(j) // see the new value of j
}
4.2 结构体 structs
A struct
is a collection of fields.
package main
import "fmt"
type Vertex struct {
X int
Y int
}
func main() {
fmt.Println(Vertex{1, 2})
}
4.3 结构体域 struct fields
Struct fields are accessed using a dot.
package main
import "fmt"
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{1, 2}
v.X = 4
fmt.Println(v.X)
}
4.4 指向结构体的指针
Struct fields can be accessed through a struct pointer.
To access the field X
of a struct when we have the struct pointer p we could write (*p).X
. However, that notation is cumbersome, so the language permits us instead to write just p.X
, without the explicit dereference.
指针p
,可以直接写p.x
package main
import "fmt"
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{1, 2}
p := &v
p.X = 1e9
fmt.Println(v)
}
4.5 结构体的字面值
A struct literal denotes a newly allocated struct value by listing the values of its fields.
You can list just a subset of fields by using the Name: syntax. (And the order of named fields is irrelevant.)
The special prefix & returns a pointer to the struct value.
package main
import "fmt"
type Vertex struct {
X, Y int
}
var (
v1 = Vertex{1, 2} // has type Vertex
v2 = Vertex{X: 1} // Y:0 is implicit
v3 = Vertex{} // X:0 and Y:0
p = &Vertex{1, 2} // has type *Vertex
)
func main() {
fmt.Println(v1, p, v2, v3)
}
4.6 数组
The type [n]T
is an array of n
values of type T
.
The expression
var a [10]int
declares a variable a as an array of ten integers.
An array’s length is part of its type, so arrays cannot be resized. This seems limiting, but don’t worry; Go provides a convenient way of working with arrays.
package main
import "fmt"
func main() {
var a [2]string
a[0] = "Hello"
a[1] = "World"
fmt.Println(a[0], a[1])
fmt.Println(a)
primes := [6]int{2, 3, 5, 7, 11, 13}
fmt.Println(primes)
}
4.7 切片 Slices
An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array. In practice, slices are much more common than arrays.
The type []T
is a slice with elements of type T
.
A slice is formed by specifying two indices, a low and high bound, separated by a colon:
a[low : high]
This selects a half-open range which includes the first element, but excludes the last one.
切片左闭右开
The following expression creates a slice which includes elements 1 through 3 of a:
a[1:4]
package main
import "fmt"
func main() {
primes := [6]int{2, 3, 5, 7, 11, 13}
var s []int = primes[1:4]
fmt.Println(s)
}
答案是[3 5 7]
4.8 切片就像是数组的索引 Slices are like references to arrays
A slice does not store any data, it just describes a section of an underlying array.
Changing the elements of a slice modifies the corresponding elements of its underlying array.
Other slices that share the same underlying array will see those changes.
package main
import "fmt"
func main() {
names := [4]string{
"John",
"Paul",
"George",
"Ringo",
}
fmt.Println(names)
a := names[0:2]
b := names[1:3]
fmt.Println(a, b)
b[0] = "XXX"
fmt.Println(a, b)
fmt.Println(names)
}
4.9 切片字面值 Slice literals
A slice literal is like an array literal without the length.
This is an array literal:
[3]bool{true, true, false}
And this creates the same array as above, then builds a slice that references it:
[]bool{true, true, false}
slice_literals.go
package main
import "fmt"
func main() {
q := []int{2, 3, 5, 7, 11, 13}
fmt.Println(q)
r := []bool{true, false, true, true, false, true}
fmt.Println(r)
s := []struct {
i int
b bool
}{
{2, true},
{3, false},
{5, true},
{7, true},
{11, false},
{13, true},
}
fmt.Println(s)
}
4.10 slice defaults
When slicing, you may omit the high or low bounds to use their defaults instead.
The default is zero for the low bound and the length of the slice for the high bound.
For the array
var a [10]int
these slice expressions are equivalent:
a[0:10]
a[:10]
a[0:]
a[:]
slice_bounds
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
s = s[1:4]
fmt.Println(s)
s = s[:2]
fmt.Println(s)
s = s[1:]
fmt.Println(s)
}
4.11 切片长度和容量 Slice length and capacity
A slice has both a length and a capacity.
The length of a slice is the number of elements it contains.
The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.
The length and capacity of a slice s can be obtained using the expressions len(s)
and cap(s)
.
You can extend a slice’s length by re-slicing it, provided it has sufficient capacity.
Try changing one of the slice operations in the example program to extend it beyond its capacity and see what happens.
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)
// Slice the slice to give it zero length.
s = s[:0]
printSlice(s)
// Extend its length.
s = s[:4]
printSlice(s)
// Drop its first two values.
s = s[2:]
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
4.12 nil slices
The zero value of a slice is nil.
A nil slice has a length and capacity of 0 and has no underlying array.
package main
import "fmt"
func main() {
var s []int
fmt.Println(s, len(s), cap(s))
if s == nil {
fmt.Println("nil!")
}
}
4.13 creating a slice with make
Slices can be created with the built-in make
function; this is how you create dynamically-sized arrays.
The make
function allocates a zeroed array and returns a slice that refers to that array:
a := make([]int, 5) // len(a)=5
To specify a capacity, pass a third argument to make:
b := make([]int, 0, 5) // len(b)=0, cap(b)=5
b = b[:cap(b)] // len(b)=5, cap(b)=5
b = b[1:] // len(b)=4, cap(b)=4
package main
import "fmt"
func main() {
a := make([]int, 5)
printSlice("a", a)
b := make([]int, 0, 5)
printSlice("b", b)
c := b[:2]
printSlice("c", c)
d := c[2:5]
printSlice("d", d)
}
func printSlice(s string, x []int) {
fmt.Printf("%s len=%d cap=%d %v\n",
s, len(x), cap(x), x)
}
4.14 Slices of slices
Slices can contain any type, including other slices.
package main
import (
"fmt"
"strings"
)
func main() {
// Create a tic-tac-toe board.
board := [][]string{
[]string{"_", "_", "_"},
[]string{"_", "_", "_"},
[]string{"_", "_", "_"},
}
// The players take turns.
board[0][0] = "X"
board[2][2] = "O"
board[1][2] = "X"
board[1][0] = "O"
board[0][2] = "X"
for i := 0; i < len(board); i++ {
fmt.Printf("%s\n", strings.Join(board[i], " "))
}
}
4.15 Appending to a slice
It is common to append new elements to a slice, and so Go provides a built-in append
function. The documentation of the built-in package describes append
.
func append(s []T, vs ...T) []T
The first parameter s
of append
is a slice of type T
, and the rest are T
values to append to the slice.
The resulting value of append
is a slice containing all the elements of the original slice plus the provided values.
If the backing array of s
is too small to fit all the given values a bigger array will be allocated. The returned slice will point to the newly allocated array.
(To learn more about slices, read the Slices: usage and internals article.)
package main
import "fmt"
func main() {
var s []int
printSlice(s)
// append works on nil slices.
s = append(s, 0)
printSlice(s)
// The slice grows as needed.
s = append(s, 1)
printSlice(s)
// We can add more than one element at a time.
s = append(s, 2, 3, 4)
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
4.16 range
The range form of the for loop iterates over a slice or map.
When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.
package main
import "fmt"
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)
}
}
4.17 Range continued
You can skip the index or value by assigning to_
.
If you only want the index, drop the , value
entirely.
package main
import "fmt"
func main() {
pow := make([]int, 10)
for i := range pow {
pow[i] = 1 << uint(i) // == 2**i
}
for _, value := range pow {
fmt.Printf("%d\n", value)
}
}
4.18 练习:切片 【二维数组的操作】
Implement Pic
. It should return a slice of length dy
, each element of which is a slice of dx
8-bit unsigned integers. When you run the program, it will display your picture, interpreting the integers as grayscale (well, bluescale) values.
The choice of image is up to you. Interesting functions include (x+y)/2
, x*y
, and x^y
.
(You need to use a loop to allocate each []uint8
inside the [][]uint8
.)
(Use uint8(intValue)
to convert between types.)
exercise-slice.go
package main
import "golang.org/x/tour/pic"
func Pic(dx, dy int) [][]uint8 {
ret := make([][]uint8, dy)
for i := 0; i < dy; i++ {
ret[i] = make([]uint8, dx)
for j := 0; j < dx; j++ {
ret[i][j] = uint8(i^j)
}
}
return ret
}
func main() {
pic.Show(Pic)
}
4.20 map literals
Map literals are like struct literals, but the keys are required.
package main
import "fmt"
type Vertex struct {
Lat, Long float64
}
var m = map[string]Vertex{
"Bell Labs": Vertex{
40.68433, -74.39967,
},
"Google": Vertex{
37.42202, -122.08408,
},
}
func main() {
fmt.Println(m)
}
map literals continued
If the top-level type is just a type name, you can omit it from the elements of the literal.
package main
import "fmt"
type Vertex struct {
Lat, Long float64
}
var m = map[string]Vertex{
"Bell Labs": {40.68433, -74.39967},
"Google": {37.42202, -122.08408},
}
func main() {
fmt.Println(m)
}
4.22 mutating maps
Insert or update an element in map m
:
m[key] = elem
Retrieve an element:
elem = m[key]
Delete an element:
delete(m, key)
Test that a key is present with a two-value assignment:
elem, ok = m[key]
If key
is in m
, ok
is true. If not, ok
is false
.
If key
is not in the map, then elem
is the zero value for the map’s element type.
Note: If elem
or ok
have not yet been declared you could use a short declaration form:
elem, ok := m[key]
package main
import "fmt"
func main() {
m := make(map[string]int)
m["Answer"] = 42
fmt.Println("The value:", m["Answer"])
m["Answer"] = 48
fmt.Println("The value:", m["Answer"])
delete(m, "Answer")
fmt.Println("The value:", m["Answer"])
v, ok := m["Answer"]
fmt.Println("The value:", v, "Present?", ok)
}
4.23 Exercise: Maps
Implement WordCount
. It should return a map of the counts of each “word” in the string s
. The wc.Test
function runs a test suite against the provided function and prints success or failure.
You might find strings.Fields helpful.
package main
import (
"golang.org/x/tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
ret := make(map[string]int)
arr := strings.Fields(s)
for _, val := range arr{
ret[val]++
}
return ret
}
func main() {
wc.Test(WordCount)
}
4.24 function values
Functions are values too. They can be passed around just like other values.
Function values may be used as function arguments and return values.
package main
import (
"fmt"
"math"
)
func compute(fn func(float64, float64) float64) float64 {
return fn(3, 4)
}
func main() {
hypot := func(x, y float64) float64 {
return math.Sqrt(x*x + y*y)
}
fmt.Println(hypot(5, 12))
fmt.Println(compute(hypot))
fmt.Println(compute(math.Pow))
}
4.25 function closures
Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is “bound” to the variables.
For example, the adder
function returns a closure. Each closure is bound to its own sum
variable
package main
import "fmt"
func adder() func(int) int {//该函数的返回类型是 func(int) int ?
sum := 0
return func(x int) int {
sum += x
return sum
}
}
func main() {
pos, neg := adder(), adder()
for i := 0; i < 10; i++ {
fmt.Println(
pos(i),
neg(-2*i),
)
}
}
4.26 Fibonacci closure
Let’s have some fun with functions.
Implement a fibonacci function that returns a function (a closure) that returns successive fibonacci numbers (0, 1, 1, 2, 3, 5, …).
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}