Open In App

Functions in Go Language

Last Updated : 05 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Go, functions are blocks of code that perform specific tasks, which can be reused throughout the program to save memory, improve readability, and save time. Functions may or may not return a value to the caller.

Example:

Go
package main
import "fmt"

// multiply() multiplies two integers and returns the result
func multiply(a, b int) int {
    return a * b
}

func main() {
    result := multiply(5, 10)
    fmt.Printf("multiplication: %d", result)
}

Output
multiplication: 50

Syntax

func function_name(Parameter-list)(Return_type) {
// function body...
}

Function Declaration

In Go, a function is declared with the func keyword, followed by its name, parameters, and optional return type.

Syntax

func function_name(Parameter-list)(Return_type) {
// function body...
}

For our multiply example:

func multiply(a, b int) int {
return a * b
}
  • func: Keyword to declare a function.
  • function_name: The name of the function, e.g., multiply.
  • Parameter-list: a, b int—parameters with their types.
  • Return_type: int specifies the return type.

Function Calling

To use a function, simply call it by its name with any necessary arguments. Here, multiply(5, 10) calls the function with 5 and 10 as arguments.

Example

result := multiply(5, 10)
fmt.Printf("Result of multiplication: %d", result)

Function Arguments

Go supports two ways to pass arguments to functions: Call by Value and Call by Reference. By default, Go uses call by value, meaning values are copied, and changes inside the function do not affect the caller’s variables.

Call by Value

In call by value, values of the arguments are copied to the function parameters, so changes in the function do not affect the original variables.

Example:

Go
package main
import "fmt"

func multiply(a, b int) int {
    a = a * 2 // modifying a inside the function
    return a * b
}

func main() {
    x := 5
    y := 10
    fmt.Printf("Before: x = %d, y = %d\n", x, y)
    result := multiply(x, y)
    fmt.Printf("multiplication: %d\n", result)
    fmt.Printf("After: x = %d, y = %d\n", x, y)
}

Output
Before: x = 5, y = 10
multiplication: 100
After: x = 5, y = 10

Call by Reference

In call by reference, pointers are used so that changes inside the function reflect in the caller’s variables.

Example:

Go
package main
import "fmt"

func multiply(a, b *int) int {
    *a = *a * 2 // modifying a's value at its memory address
    return *a * *b
}

func main() {
    x := 5
    y := 10
    fmt.Printf("Before: x = %d, y = %d\n", x, y)
    result := multiply(&x, &y)
    fmt.Printf("multiplication: %d\n", result)
    fmt.Printf("After: x = %d, y = %d\n", x, y)
}

Output
Before: x = 5, y = 10
multiplication: 100
After: x = 10, y = 10



Next Article

Similar Reads