In this Go tutorial we will learn about functions in Go and different types of functions.
Function is a component that can be used to make certain code is reusable. This is the basic syntax to create a function in Go.
func func_name(arg_name type, ..) return_type {
// code..
}
|
There are two main types of function including void function (function without return value) and function with return value.
In this example, the sum()
function is created to sum two numbers.
package main import ( "fmt" ) func main() { sum(4, 5) } // create a sum function with two integers as an argument func sum(a int32, b int32) { var result int32 = a + b fmt.Println("Result: ", result) } |
Output
Result: 9
Based on the code above, the sum()
function is called. Then, the sum result is printed out.
In Go, the function can return single value or two values. In this example, the average()
function is created to calculate average from many data.
package main import "fmt" func main() { // create a slice of int var data []int = []int{1, 2, 3, 4, 5} // call the average function var result int = average(data) // print out the average result fmt.Println("Average result: ", result) } func average(data []int) int { var sum int = 0 // calculate the sum of all data for _, v := range data { sum += v } // calculate the average var result int = sum / len(data) // return the average result return result } |
Output
Average result: 3
Based on the code above, the average()
function is called. The average()
function returns a value with int
data type then this value is stored inside result
variable in main()
function.
The function can also returns two values. In this example, the simplePow()
function is created.
package main import ( "fmt" "math" ) func main() { // call the simplePow function // because this function returns two values // the return values are assigned in two variables result, err := simplePow(2, 3) // if error exists, show the error message if err != nil { fmt.Println("Error occurred: ", err.Error()) } // print out the result fmt.Println("Pow result: ", result) } // create simplePow function with two return values func simplePow(x, y float64) (float64, error) { // if y is not positive number if y < 0 { // throw an error return 0, fmt.Errorf("y must be positive number") } // return the pow result and nil // nil means empty or error is not exists return math.Pow(x, y), nil } |
Output
Pow result: 8
Variadic arguments is an argument that has a flexible size. This is the basic syntax of variadic arguments.
arg_name ...data_type
In this example, the sum()
function is using variadic arguments.
package main import "fmt" func main() { // call sum function with two parameters var resultOne int = sum(2, 3) // call sum function with five parameters var resultTwo int = sum(1, 2, 3, 4, 5) // print out the results fmt.Println("result from resultOne: ", resultOne) fmt.Println("result from resultTwo: ", resultTwo) } // create sum function with variadic arguments func sum(xi ...int) int { var result int = 0 for _, v := range xi { result += v } return result } |
Output
result from resultOne: 5
result from resultTwo: 15
Based on the code above, the sum()
function is created with variadic arguments to calculate the sum of all numbers in argument. Because of using variadic arguments, the sum()
function can be called with flexible number of parameters.
Variadic arguments is only allowed in the last part of the argument section in function.
// true func myFunc(a int, xi ...int) int { } // false, throw an error func coolFunc(xi ...int, a int) { } |
Recursive function is a function that call a function itself in execution. Usually, recursive function is used to solve many problems like factorial number calculation.
In this example, the factorial number calculation is using recursive function.
package main import "fmt" func main() { // call the factorial function var result int = factorial(5) // print out the result fmt.Println("Result of factorial 5: ", result) } // create a factorial function func factorial(n int) int { if n == 0 || n == 1 { return 1 } else { return n * factorial(n-1) } } |
Output
Result of factorial 5: 120
Based on the code above, there are two main components in recursive function:
Base case: base case is a case when the function is stopped. The base case of the factorial()
function is if the value of n
equals 0 or 1.
Recursive case: recursive case is a case when the function is executed. The recursive case of the factorial()
function is return n * factorial(n-1)
.
The factorial()
function works like this:
factorial(5) = 5 * factorial(4) = 5 * 4 * factorial(3) = 5 * 4 * 3 * factorial(2) = 5 * 4 * 3 * 2 * factorial(1) = 5 * 4 * 3 * 2 * 1 = 120 |
Anonymous function is also available in Go. In this example, the anonymous function is created then stored in sum
variable.
package main import ( "fmt" ) func main() { // create a func then store in sum variable sum := func(a, b int) int { return a + b } // call the function fmt.Println("Result: ", sum(4, 4)) } |
Output
Result: 8
Based on the code above, the anonymous function is called based on a variable that store an anonymous function.
The anonymous function can be executed directly. In this example, the anonymous function is created then executed directly.
package main import ( "fmt" ) func main() { // create a function then execute directly func(a, b int) { var result int = a * b fmt.Println("The result: ", result) }(4, 5) } |
Output
The result: 20
Based on the code above, the anonymous function is created to perform multiplication of two numbers. The function is executed directly with two parameters that assigned after function declaration (4, 5)
.
The higher-order function also available in Go. Higher-order function basically means a function can become an argument in another function or also known as callback.
Notice that Go is not designed for functional programming approach. In this example, the higher-order function is used in mapper()
function.
package main import ( "fmt" "strings" ) func main() { // create a slice of strings var items []string = []string{"my", "cool", "sample", "text"} // call the mapper() function with two parameters // the first parameter is a function with that returns string // the second parameter is a slice of strings var mapResult []string = mapper(func(item string) string { return strings.ToUpper(item) }, items) fmt.Println("Result from mapper: ", mapResult) } func mapper(callback func(item string) string, items []string) []string { // create an empty slice of strings called result var result []string = []string{} // execute the callback then add to result for _, v := range items { result = append(result, callback(v)) } // return the map result return result } |
Output
Result from mapper: [MY COOL SAMPLE TEXT]
Based on the code above, the mapper()
function is created with two arguments. The first argument is a callback function that will be executed inside mapper()
function. The callback function is a function with string as an argument that returns string. The second argument in mapper()
function is a slice of string. The mapper()
result is stored inside mapResult
variable.
The function can be used to reduce duplicate codes. This is the sample code.
func generateCode(text string) string { // perform simple validation if len(text) == 0 && text == "" { fmt.Println("Invalid input") return "" } var code string = strings.Split(text, "")[2] return code } func convertToUppercase(text string) string { // perform simple validation // this code is a duplicate if len(text) == 0 && text == "" { fmt.Println("Invalid input") return "" } return strings.ToUpper(text) |
}
Based on the code above, there is a duplicate code. This code can be wrapped inside a function that can be reused in other code.
func generateCode(text string) string { // call the validation() function var isNotValid bool = validation(text) if isNotValid { return "" } var code string = strings.Split(text, "")[2] return code } func convertToUppercase(text string) string { // call the validation() function var isNotValid bool = validation(text) if isNotValid { return "" } return strings.ToUpper(text) } // create a function for validation func validation(text string) bool { if len(text) == 0 && text == "" { fmt.Println("Invalid input") return false } return true } |
I hope this article is helpful to learn function in Go Programming Language.
Conclusion: In this golang tutorial we covered what are functions and different types of functions in GoLang.
Article Contributed By :
|
|
|
|
681 Views |