如何使用Golang实现函数指针_函数变量与回调示例
技术百科
P粉602998670
发布时间:2026-01-01
浏览: 次 Go中没有C风格函数指针,但函数是一等公民,可赋值、传参、返回;通过type定义函数类型,声明函数变量并赋值函数名(不带括号),支持回调、闭包及方法绑定(需显式封装)。
Go 里没有函数指针,只有函数类型和函数值
Go 不支持 C 风格的函数指针(如 int (*fn)(int)),但可以用函数类型声明变量、作为参数传递、返回或存储在结构体中——这实际就是“函数变量”和“回调”的实现基础。关键在于:函数在 Go 中是一等公民,可赋值、传参、返回,但本质是值(function value),不是地址意义上的指针。
定义函数类型并声明函数变量
用 type 定义函数签名类型,再声明该类型的变量,就能把函数赋给它:
type Handler func(string) int
func countChars(s string) int {
return len(s)
}
func main() {
var h Handler
h = countChars // 直接赋函数名(不带括号)
result := h("hello") // 调用,等价于 countChars("hello")
fmt.Println(result) // 输出 5
}
-
Handler是类型,不是别名;它描述“接受string、返回int”的函数签名 - 赋值时写
countChars,不是countChars()或&countChars - 函数变量可为
nil,调用前建议判空:if h != nil { h("x") }
将函数作为参数实现回调
把函数类型作为参数传入,就是典型的回调模式。常见于事件处理、策略注入、模板执行等场景:
func processText(text string, transform func(string) string) string {
return transform(text)
}
func toUpper(s string) string {
return strings.ToUpper(s)
}
func main() {
result := processText("go", toUpper)
fmt.Println(result) // "GO"
}
- 参数
transform是函数值,调用者决定传哪个具体函数 - 可传匿名函数:
processText("go", func(s string) string { return s + "!" }) - 闭包也完全合法:
prefix := "【"; processText("go", func(s string) string { return prefix + s })
函数类型嵌套与方法绑定容易踩的坑
函数类型不能直接调用方法,也不能和接收者混用;绑定方法需显式转换或封装:
- 错误写法:
strings.ToUpper是函数,但"abc".ToUpper()不存在 ——string类型没这个方法 - 想把方法当回调用?必须用显式接收者调用:
func(s string) string { return strings.ToUpper(s) },而不是strings.ToUpper直接赋值(虽然它类型匹配,但语义不同) - 结构体方法不能直接赋给函数变量,除非包装:
type Greeter struct{ Name string } func (g Greeter) SayHi() string { return "Hi, " + g.Name } g := Greeter{Name: "Alice"} // ❌ 错误:SayHi 是方法,需要接收者,不能直接赋值 // var f func() string = g.SayHi // ✅ 正确:用闭包捕获接收者 f := func() string { return g.SayHi() } fmt.Println(f()) // "Hi, Alice"
真正容易忽略的是:函数值底层包含代码指针 + 闭包环境(如果有),多次赋值相同函数名会创建多个独立值;若函数内引用了外部变量,要
注意生命周期和并发安全。
# ai
# 的是
# 能把
# 多个
# 不存在
# 绑定
# 可以用
# 不支持
# go
# golang
# 并发
# String
# if
# int
# 指针
# nil
# function
# 不带
# 事件
# 回调
# 封装
# 结构体
# 闭包
# transform
# 想把
相关栏目:
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
AI推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
SEO优化<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
技术百科<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
谷歌推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
百度推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
网络营销<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
案例网站<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
精选文章<?muma echo $count; ?>
】
相关推荐
- 如何使用正则表达式提取以编号开头、后接多个注解的逻
- c++怎么使用std::unique实现去重_c+
- 如何使用Golang实现聊天室消息存档_存储聊天记
- c++如何获取map中所有的键_C++遍历键值对提
- Mac如何备份到iCloud_Mac桌面与文稿文件
- Windows怎样关闭Edge新标签页广告_Win
- Python列表推导式与字典推导式教程_简化代码高
- Windows10如何查看保存的WiFi密码_Wi
- Windows10电脑怎么设置文件权限_Win10
- LINUX如何查看文件类型_Linux中file命
- php怎么下载安装后设置错误日志_phpini l
- PHP主流架构怎么集成Redis缓存_配置步骤【方
- Win11怎么设置开机问候语_自定义Win11锁屏
- c++的STL算法库find怎么用 在容器中查找指
- c++23 std::expected怎么用 c+
- 如何在 Go 中高效缓存与分发网络视频流
- 如何使用Golang defer优化性能_减少不必
- Win11怎么查看wifi信号强度_检测Windo
- 如何使用Golang实现文件追加操作_向已有文件追
- 如何在 Go 后端安全获取并验证前端存储的 JWT
- Windows怎样拦截QQ浏览器广告_Window
- php删除数据怎么加限制_带where条件删除避免
- Python数据挖掘核心算法实践_聚类分类与特征工
- VSC怎么快速定位PHP错误行_错误追踪设置法【方
- php报错怎么查看_定位PHP致命错误与警告的方法
- Win11怎么更改系统语言_Win11中文语言包下
- php怎么连接数据库_MySQL数据库连接的基础代
- Win11怎么关闭VBS安全性_Windows11
- 如何在网页无标准表格标签时高效提取结构化数据
- Mac电脑进水了怎么办_MacBook进水后紧急处
- windows 10应用商店区域怎么改_windo
- Win11怎么设置屏保_Windows 11屏幕保
- Win11怎么关闭右下角弹窗_Win11拦截系统通
- Windows10如何更改任务栏高度_Win10解
- 如何使用Golang开发基础文件下载功能_Gola
- Win10文件历史记录怎么用 Win10开启自动备
- php和redis连接超时怎么办_phpredis
- Win11怎么设置应用分屏_Windows11贴靠
- Windows10系统怎么查看显卡型号_Win10
- 静态属性修改会影响所有实例吗_php作用域操作符下
- Python异步编程高级项目教程_asyncio协
- Win11用户账户控制怎么关_Win11关闭UAC
- 如何用正则表达式精确匹配最多含一个换行符的起止片段
- Python深度学习实战教程_神经网络模型构建与训
- Win11声音太小怎么办_Windows 11开启
- Win11怎么开启窗口对齐助手_Windows11
- Mac如何解压zip和rar文件?(推荐免费工具)
- Win11怎么设置触控板手势_Windows11三
- Win11输入法选字框不见了怎么办_Win11输入
- php打包exe后无法读取环境变量_变量配置方法【

QQ客服