In this tutorial, we will learn about functions in Go. We will cover the basics of defining and using functions, including how to return values, use multiple return values, and create recursive functions.
A function in Go is a group of statements that perform a specific task. Functions help to divide the code into smaller and modular chunks, making it more organized and manageable.
Functions in Go are defined using the func
keyword, followed by the name of the function, parameters, and the return type.
func functionName(parameters) returnType {
// function body
}
A function can return a value by specifying the return type in the function signature and using the return
statement inside the function.
func add(a int, b int) int {
return a + b
}
Go functions can return multiple values by specifying multiple return types in the function signature.
func swap(x, y string) (string, string) {
return y, x
}
A function can call itself, which is known as recursion. Recursive functions are used to solve problems that can be broken down into smaller, repetitive problems.
func factorial(n int) int {
if n == 0 {
return 1
}
return n * factorial(n-1)
}
We can define and call a basic function in Go.
For example,
greet
that takes no parameters and returns no value.greet
function from the main
function.package main
import "fmt"
func greet() {
fmt.Println("Hello, Go!")
}
func main() {
greet()
}
Hello, Go!
We can define a function in Go that returns a value.
For example,
add
that takes two integer parameters and returns their sum.add
function from the main
function and print the result.package main
import "fmt"
func add(a int, b int) int {
return a + b
}
func main() {
result := add(3, 4)
fmt.Println(result)
}
7
We can define a function in Go that returns multiple values.
For example,
swap
that takes two string parameters and returns them in reversed order.swap
function from the main
function and print the results.package main
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("hello", "world")
fmt.Println(a, b)
}
world hello
We can define a recursive function in Go to solve problems that can be broken down into smaller, repetitive problems.
For example,
factorial
that takes an integer parameter and returns the factorial of that number.factorial
with the parameter decremented by 1.factorial
function from the main
function and print the result.package main
import "fmt"
func factorial(n int) int {
if n == 0 {
return 1
}
return n * factorial(n-1)
}
func main() {
fmt.Println(factorial(5))
}
120