Go语言基础| 青训营

102 阅读2分钟

Go语言基础

1. Go语言简介

  • Go语言是一种由Google开发的开源编程语言,于2009年首次发布。
  • Go以其简洁、高效、并发支持和出色的性能而闻名。

2. 基本语法要点

变量和数据类型

  • 声明变量:var variableName type
  • 基本数据类型:int, float64, string, bool
  • 常量:const constantName type = value

控制流程

  • 条件语句:if, else if, else
  • 循环语句:for, range
  • 开关语句:switch

函数

  • 声明函数:func functionName(parameters) returnType
  • 多返回值:func multipleReturns() (int, string)
  • 匿名函数:func() { /* code */ }

3. 数据结构

数组和切片

  • 数组:var arr [size]type
  • 切片:slice := make([]type, length, capacity)
  • 切片操作:slice[start:end]

映射(Map)

  • 声明映射:mapName := make(map[keyType]valueType)
  • 添加/更新键值对:mapName[key] = value
  • 删除键值对:delete(mapName, key)

结构体(Struct)

  • 定义结构体:type StructName struct { field1 type1, field2 type2 }
  • 创建结构体实例:instance := StructName{field1: value1, field2: value2}

4. 并发

  • Go内置并发模型:goroutine 和 channel。
  • 创建goroutine:go functionName()
  • 通道(channel):ch := make(chan type)

5. 错误处理

  • 错误类型:Go使用error类型来处理错误。
  • 返回错误:return result, error

6. 包和模块

  • 包:Go代码的基本组织单元,通过import语句引入。
  • 模块:通过go mod命令管理包的版本和依赖。

7. 标准库

Go标准库提供了各种功能丰富的包,包括文件处理、网络通信、数据序列化等。

8. 其他资源

9. 示例代码

goCopy code
package main

import (
	"fmt"
)

func main() {
	// 变量声明和赋值
	var num int
	num = 42

	// 控制流程
	if num > 0 {
		fmt.Println("Positive")
	} else if num < 0 {
		fmt.Println("Negative")
	} else {
		fmt.Println("Zero")
	}

	// 循环语句
	for i := 0; i < 5; i++ {
		fmt.Println(i)
	}

	// 数组和切片
	arr := [3]int{1, 2, 3}
	slice := arr[:2]

	// 映射
	person := make(map[string]int)
	person["Alice"] = 25

	// 结构体
	type Point struct {
		X, Y int
	}
	p := Point{X: 1, Y: 2}

	// 并发
	go func() {
		fmt.Println("Hello from goroutine")
	}()

	// 错误处理
	result, err := someFunction()
	if err != nil {
		fmt.Println("Error:", err)
	} else {
		fmt.Println("Result:", result)
	}
}

func someFunction() (int, error) {
	// ...
}

这份笔记只是一个入门指南,Go语言有更多的特性和概念等待去探索。继续学习和实践将帮助你更深入地理解这门语言。