Golang program to demonstrate the 'defer' keyword to add two numbers

Here, we are going to demonstrate the 'defer' keyword to add two numbers in Golang (Go Language).
Submitted by Nidhi, on March 14, 2021 [Last updated : March 02, 2023]

Use of defer keyword to add two numbers in Golang

Problem Solution:

In this program, we will use the defer keyword to execute the function in LIFO order to add two global variables and print the result on the console screen.

Program/Source Code:

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

Golang code to use 'defer' keyword to add two numbers

// Golang program to demonstrate the
// "defer" keyword to add two numbers

package main

import "fmt"

var val1 int = 0
var val2 int = 0

func setVal1() {
	val1 = 10
}

func setVal2() {
	val1 = 20
}

func sum() {
	fmt.Println("Sum: ", val1+val2)
}

func main() {
	defer sum()
	defer setVal2()
	setVal1()
}

Output:

Sum:  20

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 to execute function call in reverse order and print the sum of two global variables on the console screen.

Golang Basic Programs »



Related Programs




Comments and Discussions!

Load comments ↻






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