Go Functions

A function in Go is a set of statements that perform a specific task. It has a name, input parameters, and an optional return value. Functions help in modularizing the code and make it more readable.

Here’s an example of a function in Go that takes two integers as input and returns their sum:

func sum(x int, y int) int {
    return x + y
}

In the above code, sum is the name of the function, x and y are the input parameters, and int is the return type.

We can call the above function in another part of the code like this:

result := sum(5, 10)
fmt.Println(result)

The output of the above code will be 15.

We can also have functions with multiple return values in Go. Here’s an example:

func divide(x, y float64) (float64, error) {
    if y == 0 {
        return 0, errors.New("division by zero")
    }
    return x / y, nil
}

In the above code, the function divide takes two float64 values as input and returns a float64 value and an error. If the second input parameter is 0, it returns an error.

We can call the above function like this:

result, err := divide(10.0, 0)
if err != nil {
    fmt.Println(err)
} else {
    fmt.Println(result)
}

The output of the above code will be division by zero.

Here is an example of a Go function with input parameters and a return value:

package main

import "fmt"

func addNumbers(a int, b int) int {
    return a + b
}

func main() {
    num1 := 5
    num2 := 10

    sum := addNumbers(num1, num2)

    fmt.Printf("The sum of %d and %d is %d", num1, num2, sum)
}

In this example, we define a function called addNumbers that takes two integer parameters and returns their sum. In the main function, we declare two integer variables num1 and num2 and assign them the values 5 and 10, respectively.

We then call the addNumbers function, passing in num1 and num2 as arguments, and assign the returned value to a variable called sum. Finally, we use fmt.Printf to print out a message that includes the values of num1, num2, and sum.

When we run this program, the output will be:

The sum of 5 and 10 is 15
Follow us on social media
Follow Author