In this exercise, you'll learn how to define and use functions in Go. You'll see how to pass parameters and return values.
1. Create simple functions with or without return values.
2. Pass parameters to a function.
3. Understand the scope of local and global variables.
4. Learn how to work with functions that return multiple values.
In Go, a function is defined using the func
keyword, followed by the function name, parameters inside parentheses, and an optional return type.
func functionName(param1 type1, param2 type2) returnType {
// Function code
}
Here is an example of a function that adds two numbers and returns the sum:
func add(x int, y int) int {
return x + y
}
This function prints a message but does not return anything:
func printMessage(message string) {
fmt.Println(message)
}
Go allows a function to return multiple values. Here is an example:
func calculate(x int, y int) (int, int) {
sum := x + y
difference := x - y
return sum, difference
}
functions.go
.add
that takes two integers as parameters and returns their sum.printMessage
that takes a message as a parameter and prints it without returning a value.calculate
that takes two integers and returns their sum and difference.Once done, call these functions from the main
function and display the results in the console.
The sum of 10 and 5 is: 15
Welcome to the world of functions in Go!
The sum is: 15
The difference is: 5
Check the official Go documentation for an in-depth explanation of functions:
Go Functions Documentation🚀 Thanks for using these exercises! If you find this content helpful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊