Q:

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

belongs to collection: Golang Basic Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Golang Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Golang program to print the type of specified vari... >>
<< Golang program to demonstrate the \'defer\�...