go-tutorial

Go Functions

A function is a collection of statements that work together to complete a task. Every Go programme includes at least one main function (). You can partition your code into functions. It’s up to you how you divide your code into separate functions, but logically, each function should fulfil a specific duty.

The name, return type, and parameters of a function are all specified in a function declaration. The body of the function is defined by a function definition.

The Go standard library includes a number of built-in functions that you can use in your programme. The function len(), for example, takes various types as inputs and returns the type’s length. If you provide it a string, it will return the length of the string in bytes. The function returns the length of an array if one is supplied to it.

Methods, subroutines, and procedures are all terms for functions.

A Function’s Definition

The following is the general format of a Go function definition:

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

In the Go programming language, a function definition consists of two parts: a function header and a function body. A function’s components are listed below.

  • Fun – It begins a function’s declaration.
  • Function name – The function signature is made up of the function name as well as the parameter list.
  • Parameters − A parameter is similar to a placeholder. You pass a value to the parameter when you call a function. Actual parameter or argument refers to this value. The type, order, and number of parameters in a function are referred to as the parameter list. A function can have no parameters because parameters are optional.
  • Return Type − A function may return a list of values as its return type. The return types parameter is a list of data types for the values returned by the function. Some functions do what they’re supposed to do without returning a value. The return type is not required in this scenario.
  • Function Body − The function’s body is made up of statements that describe what the function does.

Example

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

/* function returning the max between two numbers */ 
func max(num1, num2 int) int {
/* local variable declaration */ result int
if (num1 > num2) { 
    result = num1
  } else {
    result = num2
  } 
    return result
}

Pass by Value or Call by Value and Pass By Reference or Call By Reference are the two ways to pass arguments to the function in Golang. By default, Golang passes the arguments to the function via call by value.

Basic Parameter Passing to Function Terms:

  • Actual Parameters are the parameters supplied to the function.
  • Formal Parameters are the parameters that the function receives.

Create a Go Function

In Golang, we use the func keyword to create a function.

func greet(){
  // code
}

Here, greet() is the name of the function (denoted by ()) and code inside {….} indicates the function body.

Let’s now create a function that prints Good Morning.

// Program to define a function

package main
import "fmt"

// define a function
func greet() {
  fmt.Println("Good Morning")
}

func main() {

}

When we run this program, we will not get the output.

This is because we are just defining a function. To execute a function, we need to call it first.

Function Call

We use the function’s name followed by parenthesis to call a function.

greet()

Now, let’s add a function call inside main().

// Program to define a function

package main
import "fmt"

// define a function
func greet() {
  fmt.Println("Good Morning")
}

func main() {
  // function call
  greet()
}


Output

Good Morning

This time the function runs, and we get Good Morning as output.

Pass by Value and Pass by Reference in Go

The data type of parameters can be configured with a conventional data type or a pointer when creating a method/function with parameters. This will result in the following difference in the argument supplied to the method:

Pass by Value

In Pass by Value, we can say that the original variable will ‘copy’ the value into another memory address and pass the newly formed one into the method. As a result, anything happens to the variable inside the method has no bearing on the value of the original variable.

package main
  
import "fmt"
func modify(Z int) {
    Z = 70
}
  
// Main function
func main() {
  
    var Z int = 10
     fmt.Printf("Before Function Call, value of Z is = %d", Z)

    // call by value
    modify(Z)
      
    fmt.Printf("\nAfter Function Call, value of Z is = %d", Z)
}

Output:

Before Function Call, value of Z is = 10
After Function Call, value of Z is = 10

Pass by Reference

Pass by Reference will transmit the memory location. In other words, it passes the variable’s ‘container’ to the method, so whatever occurs to the variable inside the container is passed to the method.

package main
  
import "fmt"

func modify(Z *int) {
    *Z = 70
}
  
// Main function
func main() {
  
    var Z int = 10
  
    fmt.Printf("Before Function Call, value of Z is = %d", Z)
  
    // call by Reference by passing the address of the variable Z
    modify(&Z)
  
    fmt.Printf("\nAfter Function Call, value of Z is = %d", Z)
}

Output:

Before Function Call, value of Z is = 10
After Function Call, value of Z is = 70

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.