-
包(Packages):Go语言的程序是由包组成的,包可以是函数、变量和类型的集合。每个Go程序都包含一个名为
main的包,它是程序的入口点。 -
导入包(Import Packages):使用
import关键字导入需要的包。例如,import "fmt"导入了fmt包,该包提供了格式化输入输出的功能。 -
函数(Functions):Go语言使用关键字
func定义函数。函数可以接受参数,并且可以返回一个或多个值。例如:goCopy code func add(a, b int) int { return a + b } -
变量(Variables):使用关键字
var定义变量。Go语言是静态类型语言,变量的类型在声明时确定,并且可以使用类型推断。例如:goCopy code var x int = 10 y := 20 // 使用类型推断 -
常量(Constants):使用关键字
const定义常量。常量的值在编译时确定,不能修改。例如:goCopy code const PI = 3.14159 -
控制流程(Control Flow):
-
条件语句(Conditional Statements):Go语言使用
if语句进行条件判断。例如:goCopy code if x > 0 { fmt.Println("x is positive") } else if x < 0 { fmt.Println("x is negative") } else { fmt.Println("x is zero") } -
循环语句(Loop Statements):Go语言有
for循环和range循环。for循环用于重复执行一段代码,range循环用于迭代数组、切片、映射或通道的元素。例如:goCopy code for i := 0; i < 5; i++ { fmt.Println(i) } numbers := []int{1, 2, 3, 4, 5} for index, value := range numbers { fmt.Println(index, value) } -
开关语句(Switch Statements):Go语言的
switch语句用于根据表达式的值选择执行路径。每个case子句默认是独立的,不需要使用break语句。例如:day := "Monday" switch day { case "Monday": fmt.Println("It's Monday!") case "Tuesday": fmt.Println("It's Tuesday!") default: fmt.Println("It's another day.") }
-
-
数据类型(Data Types):
- 基本数据类型(Primitive Data Types):包括整数类型(
int、int8、int16、int32、int64)、浮点数类型(float32、float64)、布尔类型(bool)、字符串类型(string)等。 - 复合数据类型(Composite Data Types):包括数组(
array)、切片(slice)、映射(map)、结构体(struct)等。
- 基本数据类型(Primitive Data Types):包括整数类型(
-
指针(Pointers):Go语言支持指针,指针保存了变量的内存地址。使用
&操作符获取变量的地址,使用*操作符获取指针指向的值。例如:x := 10 ptr := &x fmt.Println(*ptr) // 输出变量x的值 ``` 1. 结构体(Structures):结构体是一种自定义的数据类型,用于组合多个字段来表示一种数据结构。使用`type`关键字定义结构体,并使用点操作符访问结构体的字段。例如: ``` goCopy code type Person struct { Name string Age int } p := Person{Name: "Alice", Age: 25} fmt.Println(p.Name, p.Age) ``` 1. 方法(Methods):方法是与结构体关联的函数。通过为结构体定义方法,可以为其添加特定的行为。例如: ``` goCopy code type Rectangle struct { Width float64 Height float64 } func (r Rectangle) Area() float64 { return r.Width * r.Height } rect := Rectangle{Width: 10, Height: 5} fmt.Println(rect.Area()) ```