进入高阶函数

I am trying to understand higher order functions in Go. I have the following program:

package main

import "fmt"

func caller(foo func(string) string) {
    result := foo("David")
    fmt.Println(result)
}

bar := func(name string) string {
    return "Hello " + name
}

func main(){
    caller(bar)
}

When I run it:

go run higher_order_functions.go

It gives the following error:

# command-line-arguments
./higher_order_functions.go:10:1: syntax error: non-declaration statement outside function body
./higher_order_functions.go:11:5: syntax error: unexpected return, expecting )

I am expecting the output:

"Hello David"

:= assignment doesn’t work outside of function bodies.

You have to use var bar = instead.

Short variable declaration doesn't work outside of function body, here is more information about it.

Working solution to your problem could be something like below,

package main

import "fmt"

func main() {
    caller(bar)
}

func caller(foo func(string) string) {
    result := foo("David")
    fmt.Println(result)
}

func bar(s string) string {
    return "Hello " + s
}

</div>