Exercise 6: Functions in Go (Part 2)

In this exercise, you'll learn how to define and use functions in Go. You'll see how to pass parameters and return values.

Exercise Objectives:

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.

Defining a Function in Go:

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
}

Example of a Function with Return:

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
}

Example of a Function Without Return:

This function prints a message but does not return anything:

func printMessage(message string) {
    fmt.Println(message)
}

Function with Multiple Return Values:

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
}

Instructions:

  1. Create a file named functions.go.
  2. Define a function add that takes two integers as parameters and returns their sum.
  3. Define a function printMessage that takes a message as a parameter and prints it without returning a value.
  4. Define a function 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.

Expected Output:

The sum of 10 and 5 is: 15
Welcome to the world of functions in Go!
The sum is: 15
The difference is: 5

Learn More:

Check the official Go documentation for an in-depth explanation of functions:

Go Functions Documentation
← Previous Exercise Next Exercise →

🚀 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! ☕😊


☕ Buy me a coffee