Golang中这种形式的函数定义该如何理解?
Golang中这种形式的函数定义该如何理解? 我想不出一个更好(更具描述性)的标题。
我正在学习Go,有时会看到以下形式的函数定义:
func (c *currency) GetRate (ctx context.Context, rr *protos.RateRequest) (*protos.RateResponse, error) {}
我的问题是: 如果它写成这样
func GetRate (ctx context.Context, rr *protos.RateRequest) (*protos.RateResponse, error) {}
那么我会理解这是在定义一个名为“GetRate”的函数,包含参数列表和返回值。
我无法理解的是“func (c *currency)”后面跟着函数名GetRate的用法。
有人能帮我理解一下吗?
更多关于Golang中这种形式的函数定义该如何理解?的实战教程也可以访问 https://www.itying.com/category-94-b0.html
3 回复
更多关于Golang中这种形式的函数定义该如何理解?的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
这是Go语言中的方法定义,(c *currency) 表示这个方法属于 *currency 类型(currency类型的指针接收者)。
具体来说:
c是接收者变量名(通常使用类型的首字母)*currency是接收者类型(currency类型的指针)GetRate是方法名- 这个方法只能通过
currency类型的实例(或指针)来调用
示例代码:
package main
import (
"context"
"fmt"
)
// 定义currency类型
type currency struct {
name string
rate float64
}
// 方法定义 - 属于*currency类型
func (c *currency) GetRate(ctx context.Context, currencyName string) (float64, error) {
if c.name == currencyName {
return c.rate, nil
}
return 0.0, fmt.Errorf("currency not found")
}
// 普通函数定义
func GetRateStandalone(ctx context.Context, c *currency, currencyName string) (float64, error) {
if c.name == currencyName {
return c.rate, nil
}
return 0.0, fmt.Errorf("currency not found")
}
func main() {
ctx := context.Background()
// 创建currency实例
usd := ¤cy{name: "USD", rate: 1.0}
// 调用方法(通过实例)
rate1, err1 := usd.GetRate(ctx, "USD")
fmt.Printf("Method call: rate=%.2f, error=%v\n", rate1, err1)
// 调用普通函数
rate2, err2 := GetRateStandalone(ctx, usd, "USD")
fmt.Printf("Function call: rate=%.2f, error=%v\n", rate2, err2)
// 尝试调用不存在的方法会编译错误
// GetRate(ctx, "USD") // 错误:undefined: GetRate
}
输出:
Method call: rate=1.00, error=<nil>
Function call: rate=1.00, error=<nil>
关键区别:
- 方法:
func (c *currency) GetRate()- 属于类型,通过实例调用 - 函数:
func GetRate()- 独立存在,直接调用
方法可以访问接收者的字段,在面向对象编程中用于封装类型的行为。


