wymli
wymli

Reputation: 1283

What will happen when using `defer` in chained method call?

for example,

defer profile.Start().Stop()

is that equal to:

p := profile.Start()
defer p.Stop()

Upvotes: 6

Views: 1043

Answers (2)

Shailesh Suryawanshi
Shailesh Suryawanshi

Reputation: 1270

The defer in the cascaded function defer only to the last function call. The other functions will be called immediately as per the order of evaluation.

For example

func secondInteration(p *profile){
    fmt.Println("~~~~~~~~~~ Second Iteration ~~~~~~~~")
    defer p.start().stop()
    p.intermediate()
    
}

This will only defer the stop function. Start and intermediate will be evaluated as a normal execution.

The above snippet will print

~~~~~~~~~~ Second Iteration ~~~~~~~~
start
Intermediate
stop

Whereas if you have more than one deferred function, the functions will be pushed into the Stack and the last pushed defer function will be evaluated first

For example

func thirdInteration(p *profile){
    fmt.Println("~~~~~~~~~~ Third Iteration ~~~~~~~~")
    defer p.start()
    defer p.intermediate()
    defer p.stop()
}

This outputs into

~~~~~~~~~~ Third Iteration ~~~~~~~~
stop
Intermediate
start

So effectively the above code snippets are the same in this context as only one method is chained and we have one line of code.

We can find more information here on Go Blog.

The above code snippets can be found here

Upvotes: 2

cod3rboy
cod3rboy

Reputation: 882

You can defer a long chain of method calls but only the last function call will be deferred and all other calls will be evaluated immediately with the defer statement.

func foo() {
   defer A().B().C().D().E().F().G().H()
   // Only call to H() is deferred and all other function calls must be 
   // evaluated immediately to reach H.
}

For more info see Effective Go.

Upvotes: 12

Related Questions