defer 後面跟普通函數
package mainfunc main() { run()}func run() { name := "Paul" defer sayHello(name) name = "John"}func sayHello(name string) { println("Hello " + name)}// Hello Paul 只是延緩執行,實參會按照正常順序傳入函數中
defer、return 和未命名的傳回值
package mainfunc 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 mainfunc 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 mainfunc 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 mainfunc 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 mainfunc 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 mainfunc 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 因為設定了形參所以閉包內的對應的變數只是在局部生效,不會影響外部變數