×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to demonstrate the 'defer' keyword

Here, we are going to demonstrate the 'defer' keyword in Golang (Go Language). By Nidhi Last updated : March 28, 2023

The defer keyword in Golang

In this program, we will use the defer keyword with Println() function. The defer function is used to put the statement into stack then statements execute in LIFO (Last In First Out) order.

Golang code to demonstrate the example of the 'defer' keyword

The source code to demonstrate the defer keyword is given below. The given program is compiled and executed successfully.

// Golang program to demonstrate
// the "defer" keyword

package main

import "fmt"

func main() {
	defer fmt.Println("Hello")
	defer fmt.Println("Hiiii")
	fmt.Println("Good morning")
}

Output

Good morning
Hiiii
Hello

Explanation

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.

In the main() function, we used the defer keyword and execute the statements in LIFO order. The defer statement is always used with a function call.

Golang Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.