FUNCTION
/*-->Functions are introduced by the func keyword.
-->Return type, if any, comes after parameters. The return does as you expect.
-->Function can return more than 1 value*/
e.g func square(f float) float { return f*f }
func functionName(parameters) returnType { function body }
PROGRAM 1:
/*This program calls "hello" function to print a line. No parameters are passed and no values are returned*/
package main
import "fmt"
func main() {
fmt.Print("An Example for function use and call\n")
hello()
}
func hello() {
fmt.Print("say hello to function\n")
return
}
PROGRAM 2:
/*This program passes an integer value as argument and prints the value and doesnot return any value */
package main
import "fmt"
func main() {
fmt.Print("This program passes an integer value as argument and prints the value\nand doesnot return any value\n")
var i int = 3
printvalue(i)
}
func printvalue(z int) {
fmt.Print("The value passed is\n",z,"\n")
}
PROGRESS 3:
/*This program will call a function with two parameters and return the product of these two numbers*/
package main
import "fmt"
func main() {
fmt.Print("This program will call a function with two parameters and return the product of these two numbers\n")
var c = findProduct(2,3)
fmt.Print("Product is ",c,"\n")
}
func findProduct(a int,b int) int {
return a * b
}
NOTE:
*In "GO" a function can return more than one value to the called function.example is as shown below*/
PROGRESS 4:
/*Fuction takes 2 value as parameter and returns two values*/
package main
import "fmt"
func main() {
fmt.Print("Fuction takes 2 value as parameter and returns two values\n")
a,b := hello(2,3)
fmt.Print(a,"\n",b,"\n");
}
func hello(a int,b int) (int,float) {
fmt.Print(a,"\n")
fmt.Print(b,"\n")
{return 3,4.5}
}
/*Defer: wait now Run @ exit*/
package main
import "fmt"
func main() {
var a int
var b=2
a=1
c:=3
d,e:=4,5
fmt.Print(a,b,c,d,e,"\n")
f,g:=hello(a,b,c) //To show function multiple return & Scope
hello2() //To show defer
fmt.Print("--> ",a,b,c,d,e,f,g)
}
func hello(c int,a int,b int)(int,int) {
fmt.Print(c,a,b,"\n")
{return 6,7}
}
func hello2() {
a:=1
defer fmt.Print("First Defer Exiting hello2 function\n")
defer fmt.Print("second defer-->a value ",a,"\n")
a=2
fmt.Print("Entering hello2 function\n")
}
OUTPUT
1 2 3 4 5
1 2 3
Entering hello2 function
second defer-->a value 1
First Defer Exiting hello2 function
--> 1 2 3 4 5 6 7