defer 后面跟普通函数
package main
func main() {
run()
}
func run() {
name := "Paul"
defer sayHello(name)
name = "John"
}
func sayHello(name string) {
println("Hello " + name)
}
// Hello Paul 只是延缓执行,实参会按照正常顺序传入函数中
defer、return 和未命名的返回值
package main
func main() {
name := run()
println("return: name = " + name)
}
func run() (string) {
name := "Paul"
defer sayHello(&name)
name = "John"
return name
}
func sayHello(name *string) {
*name = "George"
println("Hello " + *name)
}
//Hello John 虽然实参提前传入,但是传入的是一个指针,最后执行拿到的是经过修改过的值
//Hello George
//return: name = John 未命名返回值,所以 defer 无法对返回的值进行操作的
defer、return 和命名的返回值
package main
func main() {
name := run()
println("return: name = " + name)
func run() (x string) {
name := "Paul"
x = name
defer sayHello(&x)
name = "John"
return name
}
func sayHello(name *string) {
println("Hello " + *name)
*name = "George"
println("Hello " + *name)
}
//Hello John
//Hello George
//return: name = George 因为使用命名返回值,所 defer 里面依然可以对 defer 进行操作
package main
func main() {
name := run()
println("return: name = " + name)
func run() (x string) {
name := "Paul"
x = name
defer sayHello(x)
name = "John"
return name
}
func sayHello(name string) {
println("Hello " + name)
name = "George"
println("Hello " + name)
}
//Hello Paul 延迟执行但是按照程序顺序执行,传入的实参为 Paul
//Hello George 函数内修改对外面的值没有影响
//return: name = John
defer 闭包函数
package main
func main() {
name := run()
println("return: name = " + name)
}
func run() (string) {
name := "Paul"
aFun := func() {
println("Hello " + name)
name = "George"
println("Hello " + name)
}
name = "John"
aFun()
return name
}
//Hello John 虽然闭包定义时,外部变量 name = "Paul", 但是其实只是记录是一个指针,所以最后执行的时候 name = "John"
//Hello George
//return: name = George
package main
func main() {
name := run()
println("return: name = " + name)
}
func run() (x string) {
name := "Paul"
aFun := func() {
println("Hello " + x)
x = "George"
println("Hello " + x)
}
defer aFun()
name = "John"
return name
}
//Hello John
//Hello George
//return: name = George defer 对返回值进行了修改
package main
func main() {
name := run()
println("return: name = " + name)
}
func run() (x string) {
name := "Paul"
x = name
aFun := func(x string) {
println("Hello " + x)
x = "George"
println("Hello " + x)
}
defer aFun(x)
name = "John"
return name
}
//Hello Paul 实参按照顺序拷贝传入 x = "Paul"
//Hello George
//return: name = John 因为设置了形参所以闭包内的对应的变量只是在局部生效,不会影响外部变量
有疑问加站长微信联系(非本文作者)
![](https://static.golangjob.cn/static/img/footer.png?imageView2/2/w/280)