Getting started with Go programming – Function

Today we will see golang function. The syntax of the golang function is as follows.

func functionname ( parameter such as int , string etc) (return types such as int string etc) {

}

One interesting thing about golang is that it can return multiple values. Now lets see how to write a simple function.

package main
import "fmt"

func main() {
callMe()
}
func callMe() {
fmt.Println("Hey You called me ")
}

Here the callMe is a function with no parameter and no return value hence calling it is very simple.

Now lets try an example with parameter .


package main
import "fmt"

func main() {
fmt.Println(addMe(2,3))
}

func addMe(first int, second int ) int {
 return first + second
}

Here the function addMe takes in two integer value and returns a integer output. unlike C the golang takes the datatype after variable like first int, second int .


package main
import "fmt"

func main() {
fmt.Println(addMe(2,3))
fmt.Println(addMe(1,3))
fmt.Println(addMe(2,4))
fmt.Println(addMe(3,3))

}

func addMe(first int, second int ) ( string, int) {
 value := fmt.Sprintf("The sum of %d and %d is ", first, second)
 return value, first + second
}

 

The above example takes in two parameter as input and returns two parameter as output.

Output:

 go run func_with_parameter_2.go
The sum of 2 and 3 is 5
The sum of 1 and 3 is 4
The sum of 2 and 4 is 6
The sum of 3 and 3 is 6

Here you can see that the return value is a string and an integer.

package main
import "fmt"

func main() {
fmt.Println( sumMe(1, 2))
fmt.Println( sumMe(1, 2, 3))
}

func sumMe(nums ...int ) (res int) {
fmt.Print(nums, " ")
for _, number := range nums {
res += number
}
return res
}

Here the sumMe function can take multiple arguements.  The paramater taken by sumMe is …  which is called Elipsis .  For more information about range check this link https://github.com/golang/go/wiki/Range .

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *