In this exercise, you will learn how to create and use functions in Go.
If you already have Go installed, you can proceed with the exercise. Otherwise, follow this guide to install Go: Install Go
functions.go
in your Go project folder.main()
function and print the result using fmt.Println()
.🚀 Ready to code? Let's go! 😃
package main
import "fmt"
// Function to add two numbers
func add(a int, b int) int {
return a + b
}
func main() {
result := add(5, 3) // Calling the function
fmt.Println("The sum is:", result) // Displaying the result
}
go run functions.go
1️⃣ func add(a int, b int) int
: Declares a function add
that takes two integers as input and returns an integer.
2️⃣ return a + b
: The function returns the sum of the two provided numbers.
3️⃣ result := add(5, 3)
: Calls the add
function with arguments 5 and 3 and stores the result in the variable result
.
4️⃣ fmt.Println()
: Prints the result to the console.
✅ If your program is correct, running it should display the following output:
The sum is: 8
🚀 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! ☕😊