前置问题:我们想要对一个字符串进行复制,假定原字符串为"raw" ,则每次执行该函数,就变味"rawraw"。我们这里使用三种方式来实现这个功能:
package main
import (
"fmt"
"strings"
)
// global variable
var s = "non closet func"
var s2 = "non closet func2"
func main() {
// closet function display
closet := closetFunc()
for i := 0; i < 2; i++ {
closet()
}
// global variable display
nonClosetFunc(&s)
nonClosetFunc(&s)
// local variable and function with return
s2 = nonClosetFunc2(s2)
s2 = nonClosetFunc2(s2)
}
// 为了某一个特定功能创建一个闭包函数,假设有一个局部范围内的全局变量 common
func closetFunc() func() {
var common = "this is a locally global variable"
// 返回满足某一个功能的函数
return func() {
common = strings.Repeat(common,2)
fmt.Println(common)
}
}
func nonClosetFunc(s *string) {
*s = strings.Repeat(*s, 2)
fmt.Println(*s)
}
func nonClosetFunc2(s string) string {
s = strings.Repeat(s, 2)
fmt.Println(s)
return s
}
从上面的例子可以看出来,我们使用闭包函数来实现这个功能更加优雅,而且不需要全局变量,用完就删。而且不涉及值传递和值返回操作,看起来更加优雅。具体的作用大小很难界定,还是要看具体的场景要做什么,来选择更加优雅和高效的方式来解决问题罢了。有什么其他的关于闭包的见解的小伙伴可以在下面评论哦。