Go 函数和方法怎么用?Go语言函数方法区别与示例?

文章导读
上一个 测验 下一个 Go 编程语言支持一种特殊的函数类型,称为方法。在方法声明语法中,有一个“receiver”(接收者)来表示函数的容器。这个 receiver 可以使用 . 操作符来调用函数。例如 −
📋 目录
  1. 方法的语法
  2. 示例
  3. 带有结构体类型接收者的方法
  4. 带有非结构体类型接收者的方法
  5. 带有指针接收者的方法
A A

Go - 方法



上一个
测验
下一个

Go 编程语言支持一种特殊的函数类型,称为方法。在方法声明语法中,有一个“receiver”(接收者)来表示函数的容器。这个 receiver 可以使用 . 操作符来调用函数。例如 −

方法的语法

func (variable_name variable_data_type) function_name() [return_type]{
   /* 函数体*/
}

示例

package main

import (
   "fmt" 
   "math" 
)

/* 定义一个圆 */
type Circle struct {
   x,y,radius float64
}

/* 为圆定义一个方法 */
func(circle Circle) area() float64 {
   return math.Pi * circle.radius * circle.radius
}

func main(){
   circle := Circle{x:0, y:0, radius:5}
   fmt.Printf("Circle area: %f", circle.area())
}

上述代码编译并执行后,会产生以下结果 −

Circle area: 78.539816

带有结构体类型接收者的方法

您可以创建一个带有结构体类型接收者的方法,该方法操作结构体的副本,因此方法中进行的任何更改都不会影响原始结构体。

示例

package main
import "fmt"

// Struct
type Rectangle struct {
    width, height float64
}

// 使用结构体类型接收者定义一个方法
func (rect Rectangle) Area() float64 {
    return rect.width * rect.height
}

func main() {
    rectObj := Rectangle{width: 2.4, height: 4.5}
    fmt.Println("Area of Rectangle:", rectObj.Area())
}

上述代码编译并执行后,会产生以下结果 −

Area of Rectangle: 10.799999999999999

带有非结构体类型接收者的方法

您还可以为同一包中定义的非结构体类型创建方法。

示例

package main
import "fmt"

// 基于 int 创建自定义类型
type value int

// 使用非结构体接收者定义一个方法
func (v value) cube() value {
    return v * v * v
}

func main() {
    x := value(3)
    y := x.cube()

    fmt.Println("Cube of", x, "is", y) 
}
Cube of 3 is 27

带有指针接收者的方法

您可以创建带有指针接收者的方法。这种方法会在调用者中反映方法中进行的更改。

示例

package main
import "fmt"

type student struct {
    grade string
}

// 使用指针接收者修改数据的方法
func (s *student) updateGrade(newGrade string) {
    s.grade = newGrade
}

func main() {
    s := student{grade: "B"}
    
    fmt.Println("Before:", s.grade)
    
    // 调用方法更新成绩
    s.updateGrade("A")
    
    fmt.Println("After:", s.grade)
}
Before: B
After: A