基本语法

变量

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

import (
"fmt"
"math"
)

func main() {
var a = "initial"
var b, c int = 1, 2
var d = true
var e float64
f := float32(e)

g := a + "foo"
fmt.Println(a, b, c, d, e, f)
fmt.Println(g)

const s string = "constant"
const h = 500000000
const i = 3e20 / h
fmt.Println(s, h, i, math.Sin(h), math.Sin(i))
}
1
2
3
initial 1 2 true 0 0
initialfoo
constant 500000000 6e+11 -0.28470407323754404 0.7591864109375384

分支

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

import "fmt"

func main() {
if 7%2 == 0 {
fmt.Println("7 is even")
} else {
fmt.Println("7 is odd")
}
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 one digit")
} else {
fmt.Println(num, "has multiple digits")
}
}
1
2
3
7 is odd
8 is divisible by 4
9 has one digit
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"
"time"
)

func main() {
a := 2
switch a {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
case 4, 5:
fmt.Println("four or five")
default:
fmt.Println("other")
}

t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("It's before noon")
default:
fmt.Println("It's after noon")
}
}

循环

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

import "fmt"

func main() {
i := 1
for {
fmt.Println("loop")
break
}
for j := 8; j < 9; j++ {
fmt.Println(j)
}
for n := 0; n < 5; n++ {
if n%2 == 0 {
continue
}
fmt.Println(n)
}
for i <= 3 {
fmt.Println(i)
i = i + 1
}
}
1
2
3
4
5
6
7
loop
8
1
3
1
2
3

数组

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

import "fmt"

func main() {
var a [5]int
a[4] = 100
fmt.Println(a[4], len(a))
b := [5]int{1, 2, 3, 4, 5}
fmt.Println(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
100 5
[1 2 3 4 5]
2d: [[0 1 2] [1 2 3]]

切片

切片是一种数据结构,它由指针,长度,容量所组成,当append时,若容量不够,切片将自动扩容并返回新的slice,故append返回一个新slice需要再赋值回去

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
package main

import "fmt"

func main() {
s := make([]string, 3)
s[0] = "a"
s[1] = "b"
s[2] = "c"
fmt.Println("get:", s[2])
fmt.Println("len:", len(s))

s = append(s, "d")
s = append(s, "e", "f")
fmt.Println(s)

c := make([]string, len(s))
copy(c, s)
fmt.Println(c)

fmt.Println(s[2:5])
fmt.Println(s[:5])
fmt.Println(s[2:])

good := []string{"g", "o", "o", "d"}
fmt.Println(good)
}
1
2
3
4
5
6
7
8
get: c
len: 3
[a b c d e f]
[a b c d e f]
[c d e]
[a b c d e]
[c d e f]
[g o o d]

map

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() {
m := make(map[string]int)
m["one"] = 1
m["two"] = 2
fmt.Println(m)
fmt.Println(len(m))
fmt.Println(m["one"])
fmt.Println(m["two"])

r, ok := m["unknown"]
fmt.Println(r, ok)

delete(m, "one")

m2 := map[string]int{
"one": 1,
"two": 2,
}
var m3 = map[string]int{"one": 1, "two": 2}
fmt.Println(m2, m3)
}

1
2
3
4
5
6
map[one:1 two:2]
2
1
2
0 false
map[one:1 two:2] map[one:1 two:2]
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() {
nums := []int{2, 3, 4}
sum := 0
for i, num := range nums {
sum += num
if num == 2 {
fmt.Println("index:", i, "num:", num)
}
}
fmt.Println(sum)

m := map[string]string{"a": "A", "b": "B"}
for k, v := range m {
fmt.Println(k, v)
}
for k := range m {
fmt.Println("key", k)
}
}
1
2
3
4
5
6
index: 0 num: 2
9
a A
b B
key a
key b

函数

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

import "fmt"

func add(a int, b int) int {
return a + b
}

func add2(a, b int) int {
return a + b
}

func exists(m map[string]string, k string) (v string, ok bool) {
v, ok = m[k]
return v, ok
}
func main() {
res := add(1, 2)
fmt.Println(res)

v, ok := exists(map[string]string{"a": "A"}, "a")
fmt.Println(v, ok)
}

1
2
3
A true

指针

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

import "fmt"

func add2(n int) {
n += 2
}

func add2ptr(n *int) {
*n += 2
}
func main() {
n := 5
add2(n)
fmt.Println(n)
add2ptr(&n)
fmt.Println(n)
}

1
2
5
7

结构体

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
package main

import "fmt"

type user struct {
name string
password string
}

func main() {
a := user{name: "wang", password: "1024"}
b := user{"wang", "1024"}
c := user{name: "wang"}
c.password = "1024"

var d user
d.name = "wang"
d.password = "1024"

fmt.Println(a, b, c, d)
fmt.Println(checkPassword(a, "haha"))
fmt.Println(checkPassword2(&a, "haha"))
}

func checkPassword(u user, password string) bool {
return u.password == password
}

func checkPassword2(u *user, password string) bool {
return u.password == password
}

1
2
3
{wang 1024} {wang 1024} {wang 1024} {wang 1024}
false
false

结构体方法

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

import "fmt"

type user struct {
name string
password string
}

func (u user) checkPassword(password string) bool {
return u.password == password
}

func (u *user) resetPassword(password string) {
u.password = password
}

func main() {
a := user{name: "wang", password: "1024"}
a.resetPassword("2048")
fmt.Println(a.checkPassword("2048"))
}

1
true

错误处理

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
package main

import (
"errors"
"fmt"
)

type user struct {
name string
password string
}

func findUser(users []user, name string) (u *user, err error) {
for _, u := range users {
if u.name == name {
return &u, nil
}
}
return nil, errors.New("not found")
}
func main() {
u, err := findUser([]user{{"wang", "1024"}}, "wang")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(u.name)

if u, err := findUser([]user{{"wang", "1024"}}, "li"); err != nil {
fmt.Println(err)
return
} else {
fmt.Println(u.name)
}
}
1
2
wang
not found

字符串

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"
"strings"
)

func main() {
a := "Hello"
fmt.Println(strings.Contains(a, "ll"))
fmt.Println(strings.Count(a, "l"))
fmt.Println(strings.HasPrefix(a, "he"))
fmt.Println(strings.HasSuffix(a, "llo"))
fmt.Println(strings.Index(a, "ll"))
fmt.Println(strings.Join([]string{"he", "llo"}, "-"))
fmt.Println(strings.Repeat(a, 2))
fmt.Println(strings.Replace(a, "e", "E", -1)) // 第四个参数n表示替换次数,<0表示完全替换
fmt.Println(strings.Split("a-b-c", "-"))
fmt.Println(strings.ToLower(a))
fmt.Println(strings.ToUpper(a))
fmt.Println(len(a))

b := "你好"
fmt.Println(len(b))
}

1
2
3
4
5
6
7
8
9
10
11
12
13
true
2
false
true
2
he-llo
HelloHello
HEllo
[a b c]
hello
HELLO
5
6

字符串格式化

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"

type point struct {
x, y int
}

func main() {
s := "hello"
n := 123
p := point{1, 2}
fmt.Println(s, n)
fmt.Println(p)

fmt.Printf("s=%v\n", s)
fmt.Printf("n=%v\n", n)
fmt.Printf("p=%v\n", p)
fmt.Printf("p=%+v\n", p)
fmt.Printf("p=%#v\n", p)

f := 3.141592653
fmt.Println(f)
fmt.Printf("%.2f\n", f)
}

1
2
3
4
5
6
7
8
9
hello 123
{1 2}
s=hello
n=123
p={1 2}
p={x:1 y:2}
p=main.point{x:1, y:2}
3.141592653
3.14

JSON处理

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
package main

import (
"encoding/json"
"fmt"
)

type userInfo struct {
Name string
Age int `json:"age"`
Hobby []string
}

func main() {
a := userInfo{Name: "wang", Age: 18, Hobby: []string{"Golang", "TypeScript"}}

buf, err := json.Marshal(a) // 序列化
if err != nil {
panic(err)
}
fmt.Println(buf)
fmt.Println(string(buf))

buf, err = json.MarshalIndent(a, "", "\t")
if err != nil {
panic(err)
}
fmt.Println(string(buf))

var b userInfo
err = json.Unmarshal(buf, &b)
if err != nil {
panic(err)
}
fmt.Printf("%#v\n", b)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
[123 34 78 97 109 101 34 58 34 119 97 110 103 34 44 34 97 103 101 34 58 49 56 44
34 72 111 98 98 121 34 58 91 34 71 111 108 97 110 103 34 44 34 84 121 112 101 8
3 99 114 105 112 116 34 93 125]
{"Name":"wang","age":18,"Hobby":["Golang","TypeScript"]}
{
"Name": "wang",
"age": 18,
"Hobby": [
"Golang",
"TypeScript"
]
}
main.userInfo{Name:"wang", Age:18, Hobby:[]string{"Golang", "TypeScript"}}

时间操作

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
package main

import (
"fmt"
"time"
)

func main() {
now := time.Now()
fmt.Println(now)

t := time.Date(2022, 3, 27, 1, 25, 36, 0, time.UTC)
t2 := time.Date(2022, 3, 27, 2, 30, 36, 0, time.UTC)
fmt.Println(t)
fmt.Println(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute())
fmt.Println(t.Format("2006-01-02 15:04:05"))

diff := t2.Sub(t)
fmt.Println(diff)
fmt.Println(diff.Minutes(), diff.Seconds())

t3, err := time.Parse("2006-01-02 15:04:05", "2022-03-27 01:25:36")
if err != nil {
panic(err)
}
fmt.Println(t3 == t)
fmt.Println(now.Unix())
}

1
2
3
4
5
6
7
8
2022-05-07 15:56:14.2128236 +0800 CST m=+0.002200001
2022-03-27 01:25:36 +0000 UTC
2022 March 27 1 25
2022-03-27 01:25:36
1h5m0s
65 3900
true
1651910174

数字解析

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

import (
"fmt"
"strconv"
)

func main() {
f, _ := strconv.ParseFloat("1.234", 64)
fmt.Println(f)

n, _ := strconv.ParseInt("111", 10, 64)
fmt.Println(n)

n, _ = strconv.ParseInt("0x1000", 0, 64)
fmt.Println(n)

n2, _ := strconv.Atoi("123")
fmt.Println(n2)
n2, err := strconv.Atoi("AAA")
fmt.Println(n2, err)

}
1
2
3
4
5
1.234
111
4096
123
0 strconv.Atoi: parsing "AAA": invalid syntax

进程信息

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

import (
"fmt"
"os"
"os/exec"
)

func main() {
fmt.Println(os.Args)
fmt.Println(os.Getenv("PATH"))
fmt.Println(os.Setenv("AA", "BB"))

buf, err := exec.Command("grep", "127.0.0.1", "/etc/hosts").CombinedOutput()
if err != nil {
panic(err)
}
fmt.Println(string(buf))
}

输出结果与启动参数和操作系统相关

实例

猜数字

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
52
53
54
55
56
57
58
59
60
61
62
63
package main

import (
"bufio"
"fmt"
"math/rand"
"os"
"strconv"
"strings"
"time"
)

/// 输入数字
func inputNumber() (int, error) {
fmt.Println("Please input your guess")
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
if err != nil {
return 0, err
}
// windows使用\r\n,*nix使用\n
input = strings.Trim(input, "\r\n")
ret, err := strconv.Atoi(input)
return ret, nil
}

/// 输出结果
func outputGuessAndSecretRelation(guess, secret int) bool {
switch {
case guess > secret:
fmt.Println("Your guess is bigger than the secret number. Please try again")
case guess < secret:
fmt.Println("Your guess is smaller than the secret number. Please try again")
default:
fmt.Println("Correct, you Legend")
return true
}
return false
}

/// 输出随机数
func outputRandNumber() int {
maxNum := 100
rand.Seed(time.Now().UnixNano())
secretNumber := rand.Intn(maxNum)
fmt.Println("The secret number is ", secretNumber)
return secretNumber
}

func main() {
secretNumber := outputRandNumber()
for {
guess, err := inputNumber()
if err != nil {
fmt.Println("Invalid input. Please enter an integer value")
return
}
fmt.Println("You guess is", guess)
if outputGuessAndSecretRelation(guess, secretNumber) {
break
}
}
}