函数是 Go 语言中代码组织和复用的基本单元,方法则是面向对象编程的重要概念。本部分将深入讲解函数和方法的各种用法,帮助你编写模块化、可复用的代码。
函数是 Go 程序的基本构建块。本章讲解:
Go 语言的函数支持灵活的参数传递方式。本章涵盖:
匿名函数和闭包是 Go 语言的强大特性。本章介绍:
方法是带有接收者的函数,是 Go 面向对象的核心。本章讲解:
接口是 Go 语言实现多态的关键机制。本章涵盖:
函数定义:
// 基本函数
func add(a, b int) int {
return a + b
}
// 多返回值
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("除数不能为零")
}
return a / b, nil
}
匿名函数与闭包:
// 匿名函数
func() {
fmt.Println("匿名函数")
}()
// 闭包
func counter() func() int {
count := 0
return func() int {
count++
return count
}
}
方法:
type Rectangle struct {
Width, Height float64
}
// 值接收者
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
// 指针接收者
func (r *Rectangle) Scale(factor float64) {
r.Width *= factor
r.Height *= factor
}
接口:
type Shape interface {
Area() float64
}
// 接口实现(隐式)
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}