Defer is used to terminate the execution of a statement just before the function block is completed. While Exit is used to forcefully stop the program(remember, stopping the program, unlike return which only stops a block of code)
Implementation keyword defer
As briefly explained above, defer is used to delay the execution of a line of code within the scope of a function block. When the execution of the block is almost complete, the deferred statement is executed. Defer can be placed anywhere, the beginning or the end of the block. But it does not affect when it is executed, it will always be executed at the end.
package main
import "fmt"
func main() {
defer fmt.Println("halo")
}
fmt.Println("selamat datang")
The keyword defer above will terminate the execution of in effect the message
fmt.Println("hello"),
"hello" will appear after
"welcome".
The deferred statement will still appear even if the code block is dismissed midway using return. For example, as in the following code.
Top comments (0)