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