DEV Community

3129 Abhinav Kumar
3129 Abhinav Kumar

Posted on

Doubt with the defer in GOLang

package main
import "fmt"

func main(){
x:=1;

if x==1{
    fmt.Print("Hello  ");
    return 
}
defer fmt.Print("Bye");
Enter fullscreen mode Exit fullscreen mode

}
Why the output of the program is not Hello Bye. As defer statement should be executed after returning it.Please Explain?

Top comments (4)

Collapse
 
pranj010 profile image
Pranjal Verma

Program flow exits before even registering a defer call onto the stack.
Try putting defer statement before if condition.

Collapse
 
blazingbits profile image
BlazingBits

This is likely the problem.

The compiler is ignoring anything after the return, if you move the defer above your return statement is should work as expected.

Collapse
 
abhinavkumar profile image
3129 Abhinav Kumar

Thanks @blazingbits for your reply.

Collapse
 
abhinavkumar profile image
3129 Abhinav Kumar

Thanks @pranj010 for reply.