DEV Community

Cover image for Function values in Go
bluepaperbirds
bluepaperbirds

Posted on

Function values in Go

In the Go programming language, functions are values. That means that you can pass a function as parameter in a function.

For example, you can define a function mul which multiplies x and y. Then it returns the result.

mul := func(x, y float64) float64 {
    return x*y
}

Then you could assign the output to a variable and output it

var a float64
a = mul(3,5)
fmt.Println(a)

However, you can directly output it as a result to the print function

fmt.Println(mul(5, 12))

The program would then be:

package main

import (
    "fmt"
)

func main() {
    mul := func(x, y float64) float64 {
        return x*y
    }
    fmt.Println(mul(5, 12))
}

This results in:

60

Program exited.

Related links:

Top comments (0)