Go Function Example

1. Introduction

In the Go programming language, functions play a crucial role in structuring and organizing code. They enable programmers to encapsulate logic that can be reused and tested independently. Today, we'll look at an example of how to define and use a Go function.

Definition

A function in Go is declared with the func keyword, followed by the function's name, parameters, and return type. Functions can take zero or more parameters and may return one or more values. They can be defined with or without a body, the latter being known as a function declaration.

2. Program Steps

1. Define the main function, which serves as the entry point of the program.

2. Inside the main function, declare a variable to hold the number whose factorial we wish to calculate.

3. Call a custom factorial function, passing the number as an argument.

4. Implement the factorial function to receive an integer and return its factorial as an integer.

5. Use a loop inside the factorial function to calculate the factorial of the given number.

6. Print the result of the factorial computation in the main function.

3. Code Program

// Package main defines the executable package that
// the Go runtime will use to run the program.
package main

import (
	"fmt"
)

// factorial calculates the factorial of a non-negative integer n
// and returns the result. If n is 0, the factorial is 1 by definition.
func factorial(n int) int {
	if n == 0 {
		return 1 // Base case: 0! is defined to be 1
	}
	result := 1
	for i := 2; i <= n; i++ {
		result *= i // Multiply result by i in each iteration
	}
	return result
}

// main is the entry point of the program.
func main() {
	number := 5 // Define the number to calculate the factorial of
	fact := factorial(number) // Calculate factorial by calling the function
	fmt.Printf("The factorial of %d is %d\n", number, fact) // Print the result
}

Output:

The factorial of 5 is 120

Explanation:

1. The package main indicates the default package for an executable Go program.

2. import "fmt" is used to include the Format library, which provides I/O functionalities.

3. The factorial function is defined to take an int and return an int. It computes the factorial of the given number.

4. Inside the factorial function, a conditional check determines if n equals 0, returning 1 since the factorial of 0 is 1.

5. The variable result is initialized to 1. It will store the computed factorial.

6. A for loop iterates from 2 to n, multiplying result by the loop counter i in each iteration.

7. The main function declares a variable number with the value 5.

8. The factorial function is invoked with number as the argument, and the result is stored in fact.

9. Finally, fmt.Printf prints out the formatted result showing the factorial of the number.


Comments