Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Functions
2.1.
Defining a Function
2.2.
Example
2.3.
Calling a Function
2.4.
Example
2.5.
Returning Multiple Values from a Function
2.6.
Example
2.7.
Function Arguments
2.7.1.
Call by value
2.7.2.
Call by reference
2.8.
Function Usage
2.8.1.
Function as Value
2.8.2.
Function Closures
2.8.3.
Method
3.
Packages
3.1.
Important Points
3.2.
Import Paths
3.3.
Package Declaration
3.4.
Import Declaration
3.5.
Blank Import
3.6.
Nested Packages
3.7.
Giving Names to the Packages
3.8.
Example
4.
Recursion
4.1.
Syntax
4.2.
Examples of Recursion in Go
5.
Closure
5.1.
Example
6.
FAQs
7.
Key Takeaways
Last Updated: Mar 27, 2024

Functions, Packages, Recursion & Closure

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

In this blog, we discuss Functions, Packages, Recursion & Closure. Recursion is the process of repeating objects in a self-similar manner. At the same time, a function is a sequence of statements that together execute a task., recursion is the way of repeating items in a self-similar way, A package is a group of similar kinds of classes, interfaces, and sub-packages, A closure is a combination of the function bundled together with references to its surrounding state.

Functions

A function is a collection of all statements that work together to complete a task. Every Go program must have at least one main function (). You can break up your written code into different functions. It's up to you how you divide your code into distinct functions, but logically, each function should be responsible for a specific duty.

A function declaration specifies the function name, return type, and parameters to the compiler. A function definition defines the body of the function.

Defining a Function

In the Go programming language, a function definition takes the following general form:

func function_name( [parameter list] ) [return_types]
{
   body of the function
}

A function definition in the Go programming language consists of a function header and a function body. All of the components of the function are listed here.

Func- It is used to begin the declaration of a function.

Function Name - The function's name is what it says on the tin. The function signature is made by the function name and the argument list.

Parameters - A parameter is similar to a placeholder. You pass a value to the parameter when you call a function. An actual parameter or argument is the name given to this value. The type, order, and a number of parameters in a function are referred to as the parameter list. Parameters are optional, a function may or may not have them.

Return Type - A function may return a list of values as its return type. The data types of the values returned by the function are listed in return types. Some functions do what they're supposed to do yet don't return a value. The return type is used in this situation.

Example

A function called max is shown in the source code below (). This way accepts two parameters, num1 and num2, and returns the max difference between them-

// function definition
func max(n1 int, n2 int) int {
  
  if(n1 > n2){
      return n1
  }
  return n2
}

This example is for a function returning the max between two numbers.

Calling a Function

You declare the function's purpose when you create it in Go. To use a function, you must first call it to complete the specified task.

When a program calls a function, control is passed from the calling program to the called function. A called function completes a defined task and returns program control to the main program when its return statement or function-ending closing brace is reached.

You only need to give the relevant parameters along with the function name to call it. You can save the returned value if the function returns a value.

Example

// function definition
func max(n1 int, n2 int) int {
  
  if(n1 > n2){
      return n1
  }
  return n2
}
func main() {
  // function call
  result := max(21, 13)
  fmt.Println("Maximum is:",result)
}

Output

Maximum is: 21

This example for function returns the max between two numbers. 

Returning Multiple Values from a Function

Example

package main
import "fmt"
func swap(x string, y string) (string, string) {
   return y, x
}
func main() {
   a, b := swap("Rajesh", "Kumar")
   fmt.Println(a, b)
}

Output

Kumar Rajesh

This example for the A Go function can return multiple values. 

Function Arguments

If a function is going to use arguments, it has to declare variables that will receive the arguments' values. These variables are known as the function's formal parameters.

The formal parameters are produced when the function is entered and removed when it is exited, just like any local variables inside the function.

Arguments can be provided to a function in two different ways when calling it.

Call by value

This method inserts the real value of an argument into the formal parameter of a function. Changes to the parameter in the function have no effect on the argument in this situation.

Call by reference

The address of an argument is put into the formal parameter by this approach. The address is utilized within the function to obtain the actual parameter used in the call. This implies that changes to the parameter have an impact on the argument.

Function Usage

A function can use in the following ways:

Function as Value

Functions can create on the fly and can be used as values.

Function Closures

Functions closures are anonymous functions and can be used in dynamic programming.

Method

Methods are special functions with a receiver.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Packages

The Go language's most powerful feature is its package system. A package's objective is to develop and maintain a large number of programs by grouping related features into single units that are easy to maintain and comprehend while remaining independent of the other package programs. They can share and reuse because of the modularity. In the Go language, every package is defined with a different name, and that name is close to their functionality like the "strings" package, and it contains methods and functions that are only related to strings.

Important Points

Import Paths

In the Go language, every package is defined by a unique string, and this string is known as the import path. With the help of an import path, you can import packages inside your program. 

For example:

import "fmt"

You're importing an fmt package into your program with this sentence. Packages have a one-of-a-kind import path around the world. The package path should start with the internet domain name of the entity that owns or provides the package to avoid conflicts with the path of other packages other than the standard library.

For example:

import "CodingNinjas.com/example/strings"

Package Declaration

Package declaration is always present at the beginning of the source file in the Go language. The aim of this declaration is to determine the package's default identification when it is imported by another package.

For example:

package main

Import Declaration

Following the package, the declaration follows the import declaration. Each import declaration defines the path of one or more packages in a bracket in the Go source file, and each import declaration comprises zero or more import declarations.

For example:

// Importing a single package
import "fmt"
// Importing the multiple packages
import
(
"fmt"
"strings"
“bytes"
) 

When you import a package into your program, you get access to all of its members. When you import a package named "sort" into your program, for example, you will be able to use it. Float64s(), sort.SearchStrings(), etc functions of that package.

Blank Import

In Go programming, we sometimes import packages that we don't use in our program. The compiler will throw an error if you run such applications that contain unnecessary packages. As a result, we utilize a blank identifier before the package's name to avoid this problem.

For example:

import _ "strings."

It is known as a blank import. It's useful when the main application needs to enable extra functionality given by the blank importing additional packages at compile time.

Nested Packages

You can construct a package inside another package in the Go language by simply creating a subdirectory. The nested package, like the base package, can import.

Example:

import "math/cmplx"

The math package is the main package, and the complex package is the nested package.

Some packages may have the same names as others, but their paths are always different. Both the math and crypto packages, for example, have a rand named package, but the path to it is different, i.e., math/rand and crypto/rand.

Giving Names to the Packages

When naming a package in Go, you must always keep the following points in mind:

When you create a package, the package's name must be short and simple. 

 

For example, strings, time, flag, etc., are standard library packages.

The package name should be descriptive and unambiguous.
 

Always try to avoid choosing names commonly used or used for local relative variables.

The name of the package is generally in the singular form. Some packages, such as strings, bytes, and buffers, are named in plural form because of the need to avoid keyword clashes.

Always stay away from package names that have other meanings.

Example

// Go program to illustrate the
// concept of packages
// Package declaration
package main
  
// Importing multiple packages
import (
    "bytes"
    "fmt"
    "sort"
)
func main() {  
    // Creating and initializing slice
    // Using shorthand declaration
    slice_1 := []byte{'*', 'C', 'o', 'd', 'i', 'n', 'g',
        'N', 'i', 'n', 'j', 'a', 's', '^', '^'}
    slice_2 := []string{"Cod", "ing", "Nin", "jas"}
  
    // Displaying slices     
    fmt.Println("Original Slice:")
    fmt.Printf("Slice 1 : %s", slice_1)
    fmt.Println("\nSlice 2: ", slice_2)
  
    // Trimming specified leading
    // and trailing Unicode points
    // from the given slice of bytes
    // Using Trim function
    res := bytes.Trim(slice_1, "*^")
    fmt.Printf("\nNew Slice : %s", res)
  
    // Sorting slice 2
    // Using Strings function
    sort.Strings(slice_2)
    fmt.Println("\nSorted slice:", slice_2)
}

Output:

Original Slice:
Slice 1 : *CodingNinjas^^
Slice 2: [Cod ing Nin jas]


New Slice: CodingNinjas
Sorted slice: [Cod ing Nin jas]

Recursion

The way of repeating objects in a self-similar manner is known as recursion. A similar approach can be applied to programming languages. A recursive function call occurs when a program allows you to call a function from within another function.

Syntax

func recursion() 
{
   recursion() /* function calls itself */
}
func main() {
   recursion()
}

Recursion is supported in the Go programming language. It permits a function to call itself, in other words. However, while utilizing recursion, programmers must ensure that the function has an exit condition. Otherwise, it will continue to loop indefinitely.

Many mathematical problems, such as computing the factorial of a number or constructing a Fibonacci series, can be solved using recursive functions.

Examples of Recursion in Go

package main
import "fmt"
func factorial(i int)int {
   if(i <= 1) {
      return 1
   }
   return i * factorial(i - 1)
}
func main() { 
   var i int = 15
   fmt.Printf("Factorial of %d is %d", i, factorial(i))
}

Output

Factorial of 15 is 1307674368000

The above code calculates the factorial of a number using a recursive function.

Closure

Go programming language supports anonymous functions, which can act as function closures. Anonymous functions are used to define a function inline without passing any name to it.

In our example, we created a function get sequence(), which returns another function. This function aims to close over variable i of the upper function to form a closure. 

Example

package main
import "fmt"
func getSequence() func()int {
    i:=0
    return func () int {
        i=i+1
        return i  
   }
}
func main(){
    nextNumber := getSequence()
    /* invoke nextNumber to increase i by 1 and return the same */
   fmt.Println(nextNumber())
   fmt.Println(nextNumber())
   fmt.Println(nextNumber())
   
   nextNumber1 := getSequence()  
   fmt.Println(nextNumber1())
   fmt.Println(nextNumber1())
}

Output

1
2
3
1
2

FAQs

  1. What are packages in a Go program?
    Ans: Packages (pkg) are directories that contain Go source files or other packages in your Go workspace. The linked package stores every function, variable, and type from your source files.
     
  2. What are function closures?
    Ans: Function closures are functions that refer to variables outside the body of the function. The function has access to the referenced variables and can assign values to them.
     
  3. Can you return multiple values from a function?
    Ans: Yes. A Go function can return multiple values separated by commas in the
    return statement.
     
  4. Why is the main package always at the top of the program in Go programming? 
    Ans: Because the main package instructs the go build to use the linker in order to create an executable file

Key Takeaways

In this article, we have extensively discussed Functions, Packages, Recursion & Closure topics, and all the types of them, and learned about the use of all them.

"We hope that this blog enhances your knowledge regarding Functions, Packages, Recursion & Closure, and if you would like to learn more, check out our articles on Recursion in C++. Do upvote our blog to help other ninjas grow. Happy Coding!"

Live masterclass