GO语言

104 阅读3分钟

Go 程序的基本结构通常包括:

  • package main:指定当前包是 main,它表示该文件是一个可执行程序。
  • import "fmt" :导入标准库中的 fmt 包,用于格式化输入输出。
  • func main()main 函数是程序的入口点。

示例代码:

goCopy Code
package main

import "fmt"

func main() {
    fmt.Println("Hello, Go!")
}

2. 变量声明

Go 提供了多种变量声明方式:

  • 使用 var 显式声明:
goCopy Code
var x int
var y string
x = 10
y = "Hello"
  • 使用简短声明方式(Go 会自动推断类型):
goCopy Code
x := 10
y := "Hello"
  • 多个变量声明:
goCopy Code
var x, y int = 1, 2
a, b := 3, "world"

3. 数据类型

Go 是静态类型语言,但支持类型推导。常见的数据类型包括:

  • 基本类型:intfloat64stringbool
  • 复合类型:数组、切片、映射(map)、结构体(struct)、通道(channel)

示例代码:

goCopy Code
var age int = 25
var pi float64 = 3.14159
var name string = "Alice"
var isActive bool = true

4. 控制结构

  • 条件语句
goCopy Code
if x > 10 {
    fmt.Println("x is greater than 10")
} else if x == 10 {
    fmt.Println("x is equal to 10")
} else {
    fmt.Println("x is less than 10")
}
  • 循环语句:Go 中只有 for 循环,类似其他语言中的 while 和 do-while
goCopy Code
for i := 0; i < 5; i++ {
    fmt.Println(i)
}

无限循环:

goCopy Code
for {
    // 无限循环
}

5. 函数

  • 无参数函数:
goCopy Code
func sayHello() {
    fmt.Println("Hello!")
}
  • 带参数的函数:
goCopy Code
func add(a int, b int) int {
    return a + b
}
  • 多返回值函数:
goCopy Code
func divide(a, b int) (int, int) {
    return a / b, a % b
}

6. 数组和切片

  • 数组:固定长度的数组:
goCopy Code
var arr [3]int = [3]int{1, 2, 3}
  • 切片:动态大小的数组,可以自动扩展:
goCopy Code
slice := []int{1, 2, 3}
slice = append(slice, 4) // 向切片添加元素

7. Map(映射)

Go 的 map 是一个哈希表,用于存储键值对。

goCopy Code
m := make(map[string]int)
m["apple"] = 5
m["banana"] = 3
fmt.Println(m["apple"])  // 输出: 5

8. 结构体(Struct)

结构体是 Go 中的复合数据类型,类似于其他语言中的类。

goCopy Code
type Person struct {
    Name string
    Age  int
}

func main() {
    p := Person{Name: "Alice", Age: 25}
    fmt.Println(p.Name)  // 输出: Alice
    fmt.Println(p.Age)   // 输出: 25
}

9. 接口(Interface)

Go 中的接口定义了方法集合,结构体实现接口时不需要显式声明。Go 支持面向接口编程。

goCopy Code
type Speaker interface {
    Speak() string
}

type Person struct {
    Name string
}

func (p Person) Speak() string {
    return "Hello, my name is " + p.Name
}

func introduce(s Speaker) {
    fmt.Println(s.Speak())
}

func main() {
    p := Person{Name: "Alice"}
    introduce(p)
}

10. 并发

Go 内建对并发的支持,主要通过 Goroutines 和 Channels 实现。

  • Goroutines:轻量级线程,可以通过 go 关键字启动:
goCopy Code
go func() {
    fmt.Println("This is running concurrently.")
}()
  • Channels:在 Goroutines 之间传递数据的管道:
goCopy Code
ch := make(chan int)

go func() {
    ch <- 42  // 发送数据到通道
}()

value := <-ch  // 从通道接收数据
fmt.Println(value)  // 输出: 42

11. 错误处理

Go 通过返回值而非异常来处理错误,常见做法是返回 error 类型的值。

goCopy Code
func divide(a, b int) (int, error) {
    if b == 0 {
        return 0, fmt.Errorf("cannot divide by zero")
    }
    return a / b, nil
}

result, err := divide(10, 0)
if err != nil {
    fmt.Println("Error:", err)
} else {
    fmt.Println("Result:", result)
}