#JavaInspires
😀 Hi Guys,
Welcome to java inspires.
In this post, we will see how to create and work with functions in go lang.
sample.go
//JavaInspires package main import "fmt" func main() { // invoke simple function simpleFunction() // invoke function with parameters add(2, 3) //invoke function with return value ret := multiply(2, 3) fmt.Println("multiply return value :", ret) //invoke function with multiple return values add, sub := compute(2, 3) fmt.Println("add :", add) fmt.Println("sub :", sub) //invoke variadic function fmt.Println("sum(1,2,3) = ", sum(1, 2, 3)) fmt.Println("sum(1,2,3,4) = ", sum(1, 2, 3, 4)) } // lets create a simple function func simpleFunction() { fmt.Println("Simple Function Called") } // create a function with parameters func add(a, b int) { fmt.Println("a + b = ", a+b) } //function with return value func multiply(a, b int) int { return a * b } // function with multiple return values func compute(a, b int) (int, int) { return (a + b), (a - b) } //function with variable number of parameters func sum(nums ...int) int { res := 0 for _, n := range nums { res += n } return res }
PS C:\Users\developer\Desktop> go run .\sample.go Simple Function Called a + b = 5 multiply return value : 6 add : 5 sub : -1 sum(1,2,3) = 6 sum(1,2,3,4) = 10 PS C:\Users\developer\Desktop>
THANK YOU