程序结构:从Hello World开始
1 2 3 4 5 6 7
| package main
import "fmt"
func main() { fmt.Println("Hello, 世界!") }
|
package main
:可执行程序的入口包。
import
:可多行或分组导入(如import ("fmt"; "math")
)。
- 缩进:Go强制用Tab或统一空格(推荐用
gofmt
自动格式化)。
变量声明
1 2 3
| var name string = "Alice" var age = 30 height := 175
|
注意:短声明(:=
)不能在函数外使用,未使用的变量会编译报错!
常量与iota
1 2 3 4 5 6 7 8 9 10
| const ( StatusOK = 200 PI = 3.14 )
const ( Monday = iota + 1 Tuesday Wednesday )
|
自动枚举
1 2 3 4 5 6 7
| const ( Monday = iota + 1 pass = "插入" Wednesday = iota )
fmt.Printf("%d %v %v", Monday, pass, Wednesday)
|
输出:
数据类型
类型 |
示例 |
零值 |
整型 |
int , uint8 |
0 |
浮点型 |
float64 |
0.0 |
布尔型 |
bool |
false |
字符串 |
string |
"" |
复合类型 |
数组 , 切片 , map |
nil |
示例:
1 2 3 4 5 6
| var ( isActive bool scores [3]int names []string user map[string]string )
|
注意数组和切片的区别,数组声明要固定长度,切片不能写长度
区别:数组长度不可变,切片可动态拓展
1 2
| var scores = [...]int{1,2,3,4} var scores = []int{1,2,3,4}
|
控制结构
if-else:条件可前置
1 2 3 4 5
| if score := 85; score >= 90 { fmt.Println("A") } else if score > 60 { fmt.Println("B") }
|
for循环:唯一的关键字
1 2 3 4 5 6 7 8
| for i := 0; i < 3; i++ { fmt.Println(i) }
sum := 0 for sum < 10 { sum += 2 }
|
switch:默认不穿透
1 2 3 4 5 6 7 8 9
| day := "Wed" switch day { case "Mon", "Tue": fmt.Println("工作日") case "Wed": fmt.Println("中间日") default: fmt.Println("其他") }
|
如果需要满足条件往后执行,需要fallthrough
关键字
如下:
1 2 3 4 5 6 7 8 9 10
| day := "Wed" switch day { case "Mon", "Tue": fmt.Println("工作日") case "Wed": fmt.Println("中间日") fallthrough default: fmt.Println("其他") }
|
输出:
函数:可以多返回值
1 2 3 4 5 6 7 8
| func divide(a, b float64) (float64, error) { if b == 0 { return 0, fmt.Errorf("除数不能为0") } return a / b, nil }
result, err := divide(10, 2)
|
特殊用法: