简介
什么是Go语言?:
1.高性能,高并发
2.语法简单,学习曲线平缓
3.丰富的标准库
4.完善的工具链
5.静态链接
6.快速编译
7.跨平台
8.垃圾回收
特色,特点:
- 简洁、快速、安全
- 并行、有趣、开源
- 内存管理、数组安全、编译迅速
用途:
Go 语言被设计成一门应用于搭载 Web 服务器,存储集群或类似用途的巨型中央服务器的系统编程语言。
对于高性能分布式系统领域而言,Go 语言无疑比大多数其它语言有着更高的开发效率。它提供了海量并行的支持,这对于游戏服务端的开发而言是再好不过了。
实现一个简单的服务器:
package main
import (
"net/http"
)
func main() {
http.Handle("/", http.FileServer(http.Dir(".")))
http.ListenAndServe(":8080", nil)
}
入门
Go 语言的基础组成有以下几个部分:
- 包声明
- 引入包
- 函数
- 变量
- 语句 & 表达式
- 注释
Hello World
package main
import (
"fmt"
)
func main() {
fmt.Println("hello world")
}
第一行代码package main定义了报名,每个Go应用程序都包含一个名为main的包。
下一行import “fmt” 告诉Go编译器这个程序需要使用fmt包 (函数等),fmt实现了输入输出等
func main()是程序开始执行的函数。main函数是每一个可执行程序所必须包含的,启动后执行的第一个函数。
变量
可以通过 var 变量名 定义变量
也可以显性写出变量类型
另一种方法是使用 变量名 : = 变量类型
字符串
字符串是内置类型,可以通过 “+” 加号之间拼接
整数
浮点数
布尔型
package main
import (
"fmt"
"math"
)
func main() {
var a = "inittial"
var b, c int = 1, 2
var d = true
var e float64
f := float32(e)
g := a + "for"
fmt.Println(a, b, c, d, e, f) // intitial 1 2 true 0 0
fmt.Println(g) // initialapple
const s string = "constant"
const h = 5000000
const i = 3e20 / h
fmt.Println(s, h, i, math.Sin(h), math.Sin(i))
}
效果展示图:
if else
if 后面可以加括号,写法跟c++类似,但是在编译时会自动去掉括号。
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 := 4; num < 0 {
fmt.Println(num, "is negative")
} else if num < 0 {
fmt.Println(num, "has 1 digit")
} else {
fmt.Println(num, "has multiple digits")
}
}
效果展示图:
循环
package main
import "fmt"
func main() {
i := 1
for {
fmt.Println("loop")
break
}
for j := 7; 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
}
}
效果展示图:
switch
go的switch不需要break,当它匹配到正确的匹配项时会自动跳出,
package main
import (
"fmt"
"time"
)
func main() {
a := 2
switch a {
case 1:
fmt.Println("one")
case 2:
fmt.Println("tow")
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")
}
}
效果展示图:
数组
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)
}
效果展示图: