Go语言基础
Go语言是一种编译型的静态类型语言,具有简洁的语法和高效的性能。下面是Go语言的基础语法和使用笔记: 变量和常量 声明变量: var a int a = 10
var b string = "Hello, world!"
c := 20 d := "Hello, Go!" 声明常量: const Pi = 3.1415926
const ( Monday = 0 Tuesday = 1 Wednesday = 2 Thursday = 3 Friday = 4 Saturday = 5 Sunday = 6 )
数据类型
Go语言中的基本数据类型包括:
- bool
- int、int8、int16、int32、int64
- uint、uint8、uint16、uint32、uint64
- float32、float64
- complex64、complex128
- byte(uint8的别名)
- rune(int32的别名)
控制流
if语句: if x > 10 { fmt.Println("x is greater than 10") } else if x > 5 { fmt.Println("x is greater than 5") } else { fmt.Println("x is less than or equal to 5") } for循环: for i := 0; i < 10; i++ { fmt.Println(i) }
i := 0 for i < 10 { fmt.Println(i) i++ } switch语句: switch day { case "Monday": fmt.Println("Today is Monday") case "Tuesday": fmt.Println("Today is Tuesday") case "Wednesday": fmt.Println("Today is Wednesday") case "Thursday": fmt.Println("Today is Thursday") case "Friday": fmt.Println("Today is Friday") case "Saturday": fmt.Println("Today is Saturday") case "Sunday": fmt.Println("Today is Sunday") default: fmt.Println("Invalid day") }
函数
定义函数: func add(a, b int) int { return a + b } 调用函数: c := add(1, 2)
数组和切片
定义数组: var a [5]int a[0] = 1 a[1] = 2 a[2] = 3 a[3] = 4 a[4] = 5
b := [3]string{"apple", "banana", "orange"} 定义切片: c := []int{1, 2, 3, 4, 5} d := make([]string, 3)
结构体
定义结构体: type Person struct { name string age int }
p := Person{name: "Alice", age: 30}
接口
type Shape interface { Area() float64 }
type Rectangle struct { Width float64 Height float64 }
func (r Rectangle) Area() float64 { return r.Width * r.Height }
func main() { var s Shape s = Rectangle{3, 4} fmt.Println(s.Area()) }
并发:
Go语言中的并发使用goroutine和channel实现。goroutine是轻量级的线程,可以同时运行多个goroutine,而channel是一种用来在goroutine之间传递数据的通信机制。下面是一个并发示例: func worker(id int, jobs <-chan int, results chan<- int) { for j := range jobs { fmt.Println("worker", id, "processing job", j) time.Sleep(time.Second) results <- j * 2 } }
func main() { jobs := make(chan int, 100) results := make(chan int, 100)
for w := 1; w <= 3; w++ { go worker(w, jobs, results) }
for j := 1; j <= 9; j++ { jobs <- j } close(jobs)
for a := 1; a <= 9; a++ { <-results } }
包管理
Go语言使用go mod命令来管理包依赖,可以方便地在项目中引用其他包。下面是一些常用的go mod命令:
- go mod init:初始化一个新的模块
- go mod tidy:整理模块的依赖
- go mod vendor:将模块的依赖复制到vendor目录
- go mod download:下载模块的依赖
- go mod graph:打印模块的依赖关系图