golang / tour

[mirror] A Tour of Go
BSD 3-Clause "New" or "Revised" License
1.53k stars 521 forks source link

tour: function values #1589

Open PythonCoderUnicorn opened 4 months ago

PythonCoderUnicorn commented 4 months ago

Context: https://go.dev/tour/moretypes/24

the example shown in the code editor is not an ideal example for beginners, and I do find it confusing.

func compute(fn func(float64, float64) float64) float64 {
    return fn(3, 4)
}

func main() {

    hypot := func(x, y float64) float64 {
        return math.Sqrt(x*x + y*y)
    }
    fmt.Println(hypot(5, 12))

    fmt.Println(compute(hypot))
    fmt.Println(compute(math.Pow))
}

Could the example be simpler?

I have a simpler one that gets the lesson of the function using values and can be used as a variable

func modFunc(a,b int) int {
    return a % b
}

func main() {
    mod := modFunc
    result := mod(8,3)
    fmt.Println( result )

}