create a function that returns a value in go

In Go, we can create a function that returns a value using the return keyword. The return type of the function needs to be specified before the function name.

Here's an example of how to create a function that returns an integer value:

main.go
func add(a, b int) int {
    return a + b
}
44 chars
4 lines

In the above example, the function add takes two integer parameters and returns their sum as an integer.

To call this function and print its return value, we can write the following code:

main.go
package main

import "fmt"

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

func main() {
    result := add(3, 5)
    fmt.Println(result)
}
137 chars
13 lines

In this example, we call the add function with arguments 3 and 5 and store its return value in a variable called result. We then print the value of result using the fmt.Println statement.

This will output:

main.go
8
2 chars
2 lines

indicating that the add function correctly returned the sum of 3 and 5.

gistlibby LogSnag