Go 语言基础语法

分号规则、声明方式、注释、以及 `:=` 与 `=` 的区别。

Beginner
Key PointsGo 用换行代替分号;`:=` 是声明加赋值,只能在函数内用。

分号

The compiler inserts semicolons at line ends, so you rarely write them. One trap: the opening brace must be on the same line.

Go
func main() {
	fmt.Println("ok")     // 正确
}

// 编译错误:unexpected semicolon or newline before {
// func main()
// {
// }

变量声明的四种写法

Go
var a int = 10          // 完整
var b = 20              // 类型推断
var c int               // 零值 0
d := 30                 // 短变量声明(仅函数内)

var (                   // 分组
	x, y int = 1, 2
	name     = "go"
)

fmt.Println(a, b, c, d, x, y, name)
Output
10 20 0 30 1 2 go
FormWhereNote
var x int函数内外零值初始化
x := 1仅函数内必须至少一个新变量
const x = 1函数内外编译期常量

:= 的坑

Go
// 至少一个新变量,否则报错
a := 1
// a := 2        // no new variables on left side of :=
a = 2           // 正确:赋值

// 多变量时可以只新一个
b, c := 1, 2
b, d := 3, 4    // b 是赋值,d 是新声明 —— 合法
fmt.Println(a, b, c, d)
Output
2 3 2 4
Using := in an if/for/switch init statement scopes the variable to that block — the idiomatic way to control lifetime, and a common way to shadow an outer variable.

注释与格式

Go
// 单行注释

/*
   多行注释
*/

// Package main 演示文档注释。
// 文档注释紧贴声明,且以名称开头,godoc 才会正确渲染。
package main
Bash
gofmt -w .        # 官方格式化,无参数可调
go fmt ./...

Go has exactly one style and gofmt defines it. Teams never argue about indentation or brace placement — that saves more time than it sounds.

Friends & Partners