翻译自 https://gobyexample.com/

Go by Example

Go is an open source programming language designed for building simple, fast, and reliable software.

Go by Example is a hands-on introduction to Go using annotated example programs. Check out the first example or browse the full list below.

Go by Example: Range

range用来遍历各种不同数据结构中的元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package main

import "fmt"

func main() {
// 遍历slice,同array。
nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
sum += num
}
fmt.Println("sum:", sum)

// slice和array在遍历时都会返回索引和值。
for i, num := range nums {
if num == 3 {
fmt.Println("index:", i)
}
}

// 遍历map。
kvs := map[string]string{"a": "apple", "b": "banner"}
for k, v := range kvs {
fmt.Printf("%s -> %s\n", k, v)
}

// 也可以只接收一个返回值,range会遍历map所有的key并返回。
for k := range kvs {
fmt.Println("key:", k)
}

// 对字符串进行遍历是通过unicode字节编码进行。
// 例子中的英文字符都是一个字节的长度,而中文字符‘哈’的utf8编码是三个字节长度,对应的二进制表示‘21704’,所以‘l’的索引值就是5。
for i, c := range "go哈lang" {
fmt.Println(i, c)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ go run range.go
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111
2 21704
5 108
6 97
7 110
8 103

原文链接:Go by Example: Range

翻译自 https://gobyexample.com/

Go by Example

Go is an open source programming language designed for building simple, fast, and reliable software.

Go by Example is a hands-on introduction to Go using annotated example programs. Check out the first example or browse the full list below.

Go by Example: Maps

map是golang内置关联数组类型,在其他语言中也被称为hash或字典。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main

import "fmt"

func main() {
// 使用内置的make函数定义一个map,`make(map[key-type]val-type)`
// 根据索引赋值
m := make(map[string]int)
m["k1"] = 7
m["k2"] = 13
fmt.Println("map:", m)

// 根据索引取值
v1 := m["k1"]
fmt.Println("v1:", v1)

// 获取map的长度
fmt.Println("len:", len(m))

// 内置delete函数删除map中的元素
delete(m, "k2")
fmt.Println("map:", m)

// 获取map中某个索引对应的值。
// 返回的第一个值是map中对应的值,如果存在的话,否则是map的元素类型的零值。
// 返回的第二值可选,如果k2在m中,prs为true。否则,prs为false,并且返回的第一个值是map的元素类型的零值。
// 该例中省略了第一个返回值。这种用法可以用来判断某个key是否在map中存在,如果直接使用第一返回值是无法判断返回的零值是因为key不存在还是该key对应的元素刚好是零值。
_, prs := m["k2"]
fmt.Println("prs:", prs)

// map也可以如其他元素一样定义和初始化赋值一起。
n := map[string]int{"foo": 1, "bar": 2}
fmt.Println("map:", n)
}
1
2
3
4
5
6
7
$ go run maps.go 
map: map[k1:7 k2:13]
v1: 7
len: 2
map: map[k1:7]
prs: false
map: map[foo:1 bar:2]

原文链接:Go by Example: Maps

翻译自 https://gobyexample.com/

Go by Example

Go is an open source programming language designed for building simple, fast, and reliable software.

Go by Example is a hands-on introduction to Go using annotated example programs. Check out the first example or browse the full list below.

Go by Example: Slices

slice(切片)是golang中一个很重要的数据类型,它给序列提供了比数组更加强大的功能接口。

同数组不同,切片只由包含的元素确定,跟元素个数无关。使用内置的make函数可以初始化一个空的切片。

阅读全文 »

翻译自 https://gobyexample.com/

Go by Example

Go is an open source programming language designed for building simple, fast, and reliable software.

Go by Example is a hands-on introduction to Go using annotated example programs. Check out the first example or browse the full list below.

Go by Example: Array

golang中的数组是一个特定长度的元素有序集合。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main

import "fmt"

func main() {
// 定义一个长度为5的元素类型为int的数组,元素的类型和数组的长度都是数组的属性。默认情况数组是零值,如int型的话就是数组长度个0。
var a[5] int
fmt.Println("emp:", a)

// 根据索引设置/获取数组中某项的值
a[4] = 100
fmt.Println("set:", a)
fmt.Println("get:", a[4])

// 获取数组的长度
fmt.Println("len:", len(a))

// 定义并初始化一个数组
b := [5]int{1, 2, 3, 4, 5}
fmt.Println("dcl:", b)

// 数组类型是一维的,但是可以通过复合类型来构造多维的结构。
var twoD [2][3]int
for i := 0; i < 2; i++ {
for j := 0; j < 3; j++ {
twoD[i][j] = i + j
}
}
fmt.Println("2d:", twoD)
}
1
2
3
4
5
6
7
$ go run arrays.go
emp: [0 0 0 0 0]
set: [0 0 0 0 100]
get: 100
len: 5
dcl: [1 2 3 4 5]
2d: [[0 1 2] [1 2 3]]

原文链接:Go by Example: Arrays

翻译自 https://gobyexample.com/

Go by Example

Go is an open source programming language designed for building simple, fast, and reliable software.

Go by Example is a hands-on introduction to Go using annotated example programs. Check out the first example or browse the full list below.

Go by Example: Switch

golang也有常用的switch语句。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main

import "fmt"
import "time"

func main() {
i := 2
fmt.Print("Write", i, " as ")
// 典型的switch结构
switch i {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
}

// case后可以跟多个条件,逗号分隔。也有常用的default。
switch time.Now().Weekday() {
case time.Saturday, time.Sunday:
fmt.Println("It's the weekend")
default:
fmt.Println("It's a weekday")
}

// switch后不跟条件判断语句可以模仿if/else的功能
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("It's before noon")
default:
fmt.Println("It's after noon")
}

// 变量类型判断的switch语句,其中的type是switch独有的用法。
// 主要用来判断一个interface值的类型。
whatAmI := func(i interface{}) {
switch t := i.(type) {
case bool:
fmt.Println("I'm a bool")
case int:
fmt.Println("I'm an int")
default:
fmt.Println("Don't know type %T\n", t)
}
}
whatAmI(true)
whatAmI(1)
whatAmI("hey")
}
1
2
3
4
5
6
7
$: go run switch.go
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type string

原文链接:Go by Example: Switch

翻译自 https://gobyexample.com/

Go by Example

Go is an open source programming language designed for building simple, fast, and reliable software.

Go by Example is a hands-on introduction to Go using annotated example programs. Check out the first example or browse the full list below.

Go by Example: If/Else

goalng中的if条件语句可以省略括号,但是大括号不能少。而且golang没有常用的三元运算符?:, 所以必须用if来实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import "fmt"

func main() {
// 经典的if/else
if 7%2 == 0 {
fmt.Println("7 is even")
} else {
fmt.Println("7 is odd")
}

// if
if 8%4 == 0 {
fmt.Println("8 is divisible by 4")
}

// 条件判断语句前可以执行一条语句(简直酷毙了),并且定义的变量可以在所有条件分支引用
if num := 9; num < 0 {
fmt.Println(num, "is negative")
} else if num < 10 {
fmt.Println(num, "has 1 digit")
} else {
fmt.Println(num, "has multiple digits")
}
}
1
2
3
4
$ go run if-else.go 
7 is odd
8 is divisible by 4
9 has 1 digit

原文链接:Go by Example: If/Else

翻译自 https://gobyexample.com/

Go by Example

Go is an open source programming language designed for building simple, fast, and reliable software.

Go by Example is a hands-on introduction to Go using annotated example programs. Check out the first example or browse the full list below.

Go by Example: For

for是golang唯一的循环结构。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package main

import "fmt"

func main() {
// 最常见的形式,只有一个条件。类似于PHP中的while循环
i := 1
for i <= 3 {
fmt.Println(i)
i = i + 1
}

// 经典的for循环
for j := 7; j <= 9; j++ {
fmt.Println(j)
}

// 不带任何条件的for循环,类似于PHP中的while(true)循环。除非从函数内部break或return,否则会一直循环下去。
for {
fmt.Println("loop")
break
}

// continue关键字,同PHP。停止此次循环的执行,直接进入下一次循环。
for n:= 0; n <= 5; n++ {
if n%2 == 0 {
continue
}
fmt.Println(n)
}
}
1
2
3
4
5
6
7
8
9
10
11
$ go run for.go
1
2
3
7
8
9
loop
1
3
5

原文链接:Go by Example: For

翻译自 https://gobyexample.com/

Go by Example

Go is an open source programming language designed for building simple, fast, and reliable software.

Go by Example is a hands-on introduction to Go using annotated example programs. Check out the first example or browse the full list below.

Go by Example: Constants

golang支持字符型、字符串型、布尔型和数值型的常量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import "fmt"
import "math"

// const关键字生命常量
const s string = "constant"

func main() {
fmt.Println(s)

// const常量可以在任何变量可以声明的地方声明,并且支持科学计数法等算术运算
const n = 500000000
const d = 3e20 / n
fmt.Println(d)

// 数值型常量默认没有特定的类型,可以显式声明类型,也默认会根据上下文自动确定自身类型
// 例如下面的语句`math.Sin`函数需要float64类型的参数,n就默认确定为float64类型
fmt.Println(int64(d))
fmt.Println(math.Sin(n))
}
1
2
3
4
5
$: go run constant.go
constant
6e+11
600000000000
-0.28470407323754404

原文链接:Go by Example: Constants

翻译自 https://gobyexample.com/

Go by Example

Go is an open source programming language designed for building simple, fast, and reliable software.

Go by Example is a hands-on introduction to Go using annotated example programs. Check out the first example or browse the full list below.

Go by Example: Variables

golang中的变量被显式声明,编译时会做类型检查。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

import fmt

func main() {
// 使用var关键字声明一个变量并赋值,变量名在前,类型在后
var a string = "initial"
fmt.Println(a)

// 可以一次性初始化多个变量并赋值
var b,c int = 1, 2
fmt.Println(b, c)

// golang会自动推断出未显式声明类型的变量
var d = true
fmt.Println(d)

// 初始化未赋值的变量,golang默认会赋值其相应类型的零值
var e int
fmt.Println(e)

// 也可以使用':='操作符
f := "short"
fmt.Println(f)
}
1
2
3
4
5
6
$ go run variables.go
initial
1 2
true
0
short

原文链接:Go by Example: Variables

翻译自 https://gobyexample.com/

Go by Example

Go is an open source programming language designed for building simple, fast, and reliable software.

Go by Example is a hands-on introduction to Go using annotated example programs. Check out the first example or browse the full list below.

Go by Example: Values

golang内置有多种基本数据类型,包含字符串、整型、浮点型、布尔型等等。上面是一些基本类型的示例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main

import "fmt"

func main() {
// 字符串连接
fmt.Println("go" + "lang")

// 整数加法
fmt.Println("1+1 =", 1+1)

// 浮点数除法
fmt.Println("7.0/3.0 =", 7.0/3.0)

// 逻辑运算
fmt.Println(true && false)
fmt.Println(true || false)
fmt.Println(!true)
}
1
2
3
4
5
6
7
$ go run values.go
golang
1+1 = 2
7.0/3.0 = 2.3333333333333335
false
true
false

原文链接:Go by Example: Values