0
0
Goprogramming~5 mins

Return values in Go

Choose your learning style9 modes available
Introduction
Return values let a function send back a result after it finishes its work. This helps you reuse the result elsewhere in your program.
When you want a function to give back a calculation result, like adding two numbers.
When you need to get a value from a function to use later, like a user's input processed.
When you want to check if a function succeeded or failed by returning a status.
When you want to return multiple pieces of information from one function.
Syntax
Go
func functionName(parameters) returnType {
    // code
    return value
}
The returnType shows what kind of value the function sends back.
You can return multiple values by listing types in parentheses, like (int, string).
Examples
A function that adds two integers and returns the sum.
Go
func add(a int, b int) int {
    return a + b
}
A function that returns two strings in swapped order.
Go
func swap(x, y string) (string, string) {
    return y, x
}
A function that returns a greeting message.
Go
func greet(name string) string {
    return "Hello, " + name
}
Sample Program
This program defines a function that multiplies two numbers and returns the result. The main function calls it and prints the answer.
Go
package main

import "fmt"

func multiply(a int, b int) int {
    return a * b
}

func main() {
    result := multiply(4, 5)
    fmt.Println("4 times 5 is", result)
}
OutputSuccess
Important Notes
If a function does not return anything, its return type is omitted.
You can name return values in the function signature for clarity, but it's optional.
Use return to send the value back and stop the function immediately.
Summary
Functions use return values to send results back to the caller.
You can return one or more values by specifying their types.
Return values help keep your code organized and reusable.