Go Part 5: Functions In Go

Go PART 5: Functions In Go


Please Subscribe Youtube| Like Facebook | Follow Twitter

Functions in Go

In this article, we will provide a detailed overview of Functions in Go and provide examples of how they are used in Go programming.

In Go programming language, a function is a block of code that performs a specific task. Functions help to break down complex problems into smaller, more manageable parts. They also promote code reusability and improve the readability of the code. In this article, we will discuss functions in Go and how they work.

Function Syntax In Go

func functionName(param1 type, param2 type) returnType {
  // function body
  return returnValue
}

func: This keyword is used to define a function in Go.

functionName: This is the name of the function. It should be a valid identifier in Go, such as addNumbers or calculateArea.

(param1 type, param2 type): These are the input parameters that the function accepts. You can specify multiple parameters separated by commas. Each parameter should be defined with a name and its corresponding data type. For example, (x int, y int) means that the function accepts two integer parameters named x and y.

returnType: This is the data type that the function returns. It should be defined after the closing parenthesis of the input parameters. For example, int means that the function returns an integer value.

{}: These curly braces enclose the function body, which contains the code that executes when the function is called.

return returnValue: This statement returns the value from the function. returnValue is the value that the function returns. Its data type should match the returnType specified in the function signature. If the function does not return any value, you can omit the return statement or use the keyword nil to return a null value.

Types of Functions in Go

Go supports two types of Functions:

  1. Built-in Functions
  2. User-Defined Functions

Built-in Functions: Go has a number of built-in functions that are available for use without requiring any special package imports or function definitions. These functions are part of the Go language specification and are always available to the programmer.
Some examples of built-in functions in Go include len(), cap(), append(), copy(), make(), new(), delete(), and panic().

User-Defined Functions: User-defined functions are functions that are created by the programmer for a specific purpose. These functions can be defined in any package and must be imported into the program in order to be used.

Example Function in Go

Here’s an example code with a call to both a built-in function and a user-defined function, along with their output:

package main

import "fmt"

// User-defined function that takes two integers and returns their sum
func addNumbers(x int, y int) int {
    sum := x + y
    return sum
}

func main() {
    // Call to built-in function len()
    myString := "Hello, world!"
    stringLength := len(myString)
    fmt.Println("Length of string:", stringLength)

    // Call to user-defined function addNumbers()
    result := addNumbers(5, 7)
    fmt.Println("Sum of numbers:", result)
}

Output

Length of string: 13
Sum of numbers: 12

In this example, we have a user-defined function called addNumbers() that takes two integers and returns their sum. We also have a call to the built-in function len() that returns the length of a string.

In the main() function, we call both len() and addNumbers(), passing in the appropriate parameters. We then print out the results of each function call using fmt.Println().

The output shows the length of the string and the sum of the two numbers.

Example Function in Go with no return type and no parameters

package main

import "fmt"

func printGreeting() {
    fmt.Println("Hello, world!")
}

func main() {
    printGreeting()
}

Output

Hello, world!

Passing Parameters to a Function in Go

In Go, all function arguments are passed by value, which means that a copy of the original value is passed to the function. This includes both built-in types (such as integers, floats, and booleans) and user-defined types (such as structs and arrays).

However, when passing an argument that is a reference type (such as a pointer), a copy of the memory address pointing to the value being referenced is passed to the function instead

Here are examples of both pass-by-value and pass-by-reference in Go:

Pass-by-Value Example

package main

import "fmt"

func changeValue(x int) {
    x = 10
}

func main() {
    y := 5
    fmt.Println("Before function call:", y)
    changeValue(y)
    fmt.Println("After function call:", y)
}

Output

Before function call: 5
After function call: 5

In this example, we have a function called changeValue() that takes an integer parameter x and tries to change its value to 10. We also have a variable y in the main() function that is assigned the value 5.

When we call changeValue(y) in main(), a copy of the value of y is passed to the changeValue() function as the argument for the x parameter. The function then changes the value of its own copy of x to 10, but this does not affect the value of y outside of the function.

Pass-by-Reference Example

package main

import "fmt"

func changeValue(x *int) {
    *x = 10
}

func main() {
    y := 5
    fmt.Println("Before function call:", y)
    changeValue(&y)
    fmt.Println("After function call:", y)
}

Output

Before function call: 5
After function call: 10

|In this example, we have a function called changeValue() that takes a pointer to an integer parameter x and changes the value being referenced by x to 10. We also have a variable y in the main() function that is assigned the value 5.

When we call changeValue(&y) in main(), a copy of the memory address of y is passed to the changeValue() function as the argument for the x parameter. The function then changes the value being referenced by x to 10, which also changes the value of y outside of the function.

Note that in the pass-by-reference example, we use the & operator to get the memory address of y, and the * operator in the changeValue() function to dereference the pointer and access the value being referenced by x.

Conclusion

In Go, functions are an essential building block of programs, allowing developers to group code into reusable units that can be called from anywhere in the program. Go supports both built-in functions and user-defined functions, which can take parameters and return values as needed.

Functions in Go can be declared using the func keyword, and can have a name, parameters, and a return type. Parameters can be passed to functions either by value or by reference, and return values can be single or multiple.

Overall, functions are a powerful tool in Go that allow developers to write efficient and modular code. By understanding the syntax and features of functions in Go, developers can create more robust and scalable programs.

Go Beginner Tutorial Series

Please Subscribe Youtube| Like Facebook | Follow Twitter


Leave a Reply

Your email address will not be published. Required fields are marked *