第一部分的内容是 Golang 语言的基础语法。
1.变量:
在 Golang 中,可以使用关键字 var 来声明变量,也可以使用简写语法 := 进行声明。例如:
goCopy codevar x int
x = 10
// 等价于
x := 10
2.常量:
常量是固定不变的值,在 Golang 中,使用 const 关键字来声明常量,例如:
const Pi = 3.14
3. 数据类型:
Golang 支持多种数据类型,包括整数、浮点数、字符串、布尔值等。
4.运算符:
Golang 支持常见的算术、关系和逻辑运算符,如加、减、乘、除、比较等。
5.控制结构:
Golang 中有多种控制结构,用于实现不同的流程控制,如 if/else 语句、for 循环、switch/case 语句等。
5.1. If/Else 语句:
If/Else 语句是 Golang 中常用的条件语句,用于判断某个条件是否成立,并在条件成立或不成立时执行不同的语句。语法如下:
if condition {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
其中 condition 是一个布尔表达式,可以是任何能够评估为 true 或 false 的表达式。如果 condition 为 true,则执行 if 语句块中的语句;如果 condition 为 false,则执行 else 语句块中的语句。
注意,在 Golang 中,大括号是必需的,并且必须和 if/else 语句放在同一行,否则将会产生编译错误。
例如:
package main
import "fmt"
func main() {
x := 10
if x > 5 {
fmt.Println("x is greater than 5")
} else {
fmt.Println("x is less than or equal to 5")
}
}
在这个例子中,如果变量 x 的值大于 5,则打印 “x is greater than 5”;否则,打印 “x is less than or equal to 5”。
5.2 For循环:
For 循环是 Golang 中最常用的循环语句,用于在指定的范围内重复执行一段语句。在 Golang 中,有三种不同的 For 循环语法:
- For 循环语法:
for init; condition; post {
// code to be executed
}
在每次循环中,首先执行 init 语句,然后评估 condition,如果 condition 为 true,则执行循环体,最后执行 post 语句。
- For 循环的简写语法:
for condition {
// code to be executed
}
简写语法相当于:
for ; condition; {
// code to be executed
}
在每次循环中,只需评估 condition,如果 condition 为 true,则执行循环体。
- For range 循环:
for key, value := range collection {
// code to be executed
}
For range 循环是一种特殊的循环语法,用于遍历数组、切片、字符串、map 等集合类型。在每次循环中,会将集合中的下一个元素赋值给变量 key 和 value,然后执行循环体。
例如:
package main
import "fmt"
func main() {
arr := []int{1, 2, 3, 4, 5}
for i, val := range arr {
fmt.Printf("Index: %d, Value: %d\n", i, val)
}
}
在这个例子中,For range 循环用于遍历数组 arr,并打印每个元素的索引和值。
同时需要注意的是,For 循环的简单写法。不用第三个部分,也可以写作无限循环。
例如:
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// for 循环不需要三个部分,也可以写作无限循环
j := 0
for {
fmt.Println(j)
j++
if j == 5 {
break
}
}
}
5.3 Switch / Case语句:
package main
import "fmt"
func main() {
x := 3
switch x {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
default:
fmt.Println("unknown")
}
}