dongqiu5184
2018-12-25 01:32
浏览 22
已采纳

使用延迟时函数中的返回值

I have some problem with using 'defer' about the return value. I tried to run one test function in different way (only the definition of i is different), but the result is different. So, I'm confused about the different return value. Here is the problem:

function 1:

package main
import "fmt"
func main() {
    fmt.Println("a return:", a()) // return value: 0
}

func a() int {
    var i int
    defer func() {
        i++
        fmt.Println("a defer1:", i) // print " a defer1: 1"
    }()
    return i
}

return value:

a defer1: 1
a return: 0

function 2:

package main
import "fmt"

func main() {
    fmt.Println("a return:", a()) // return value: 1
}

func a() (i int) {
    defer func() {
        i++
        fmt.Println("a defer1:", i) // print " a defer1: 1"
    }()
    return i
}

return value:

a defer1: 1
a return: 1

One of the return values is 0, the other is 1. So, the question is what's the difference between the two function.

图片转代码服务由CSDN问答提供 功能建议

我对返回值使用'defer'时遇到了一些问题。 我尝试以不同的方式运行一个测试功能(仅i的定义不同),但结果不同。 因此,我对不同的返回值感到困惑。 这是问题所在:

功能1:

 包main 
import“ fmt” 
func main(){
 fmt。  Println(“ a return:”,a())//返回值:0 
} 
 
func a()int {
 var i int 
 defer func(){
 i ++ 
 fmt.Println  (“ a defer1:”,i)//打印“ a defer1:1” 
}()
返回i 
} 
   
 
 

返回值:

 延迟1:1 \不返回:0 
   
 
 

功能2: \ n

 包main 
import“ fmt” 
 
func main(){
 fmt.Println(“ a return:”,a())//返回值:1 
} 
 \  nfunc a()(i int){
 defer func(){
 i ++ 
 fmt.Println(“ a defer1:”,i)//打印“ a defer1:1” 
}()
返回 i 
} 
   
 
 

返回值:

 延迟1:1 
a返回:1 
 <  / code>  
 
 

一个返回值是0,另一个是1。所以,问题是两个函数之间有什么区别。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongxiandi8313 2018-12-25 01:59
    已采纳

    what's the difference between the two functions?


    The Go Programming Language Specification

    Defer statements

    A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns.

    Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked. Instead, deferred functions are invoked immediately before the surrounding function returns, in the reverse order they were deferred.

    if the deferred function is a function literal and the surrounding function has named result parameters that are in scope within the literal, the deferred function may access and modify the result parameters before they are returned. If the deferred function has any return values, they are discarded when the function completes.


    The difference is a surrounding function with a named result parameter

    func a() (i int)
    

    versus a surrounding function with an unnamed result parameter

    func a() int
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题