// 指针基础
var x int = 10
var p *int = &x
*p = 20 // 修改x的值
// new函数分配内存
ptr := new(int)
*ptr = 100
// 结构体定义
type Person struct {
Name string
Age int
}
// 方法定义
func (p Person) SayHello() string {
return "Hello, " + p.Name
}
// 指针接收者
func (p *Person) SetAge(age int) {
p.Age = age
}
// 接口定义
type Shape interface {
Area() float64
Perimeter() float64
}
// 实现接口
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func (r Rectangle) Perimeter() float64 {
return 2 * (r.Width + r.Height)
}
// 错误处理模式
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
// 自定义错误类型
type MyError struct {
Code int
Message string
}
func (e MyError) Error() string {
return fmt.Sprintf("Error %d: %s", e.Code, e.Message)
}
// goroutine
func sayHello() {
fmt.Println("Hello from goroutine")
}
go sayHello() // 启动goroutine
// channel通信
ch := make(chan int)
go func() {
ch <- 42 // 发送数据
}()
value := <-ch // 接收数据
// go.mod文件示例
module github.com/username/project
go 1.19
require (
github.com/gin-gonic/gin v1.9.0
github.com/go-sql-driver/mysql v1.7.0
)
type Student struct {
ID int
Name string
Grade int
Score float64
}
// 实现增删改查功能
type StudentManager struct {
students []Student
}
func (sm *StudentManager) AddStudent(s Student) error
func (sm *StudentManager) FindStudentByID(id int) (Student, error)
func (sm *StudentManager) UpdateStudent(s Student) error
func (sm *StudentManager) DeleteStudent(id int) error
// 使用goroutine并发下载多个文件
func DownloadFiles(urls []string) error {
var wg sync.WaitGroup
errors := make(chan error, len(urls))
for _, url := range urls {
wg.Add(1)
go func(url string) {
defer wg.Done()
if err := downloadFile(url); err != nil {
errors <- err
}
}(url)
}
wg.Wait()
close(errors)
// 处理错误
return nil
}
// 使用channel实现消息广播
type ChatRoom struct {
messages chan string
clients []chan string
}
func (cr *ChatRoom) Broadcast(message string)
func (cr *ChatRoom) Join() chan string
A: 需要修改接收者状态时用指针,否则用值接收者
A: 缓冲channel可以存储多个值,非缓冲channel需要同步发送接收
A: 使用context控制goroutine生命周期,确保所有goroutine都能正常退出
完成本阶段学习后,进入第三阶段:实战模块开发