无法在golang中将函数声明为主要函数之外的变量

 收藏

正在工作的例子

package main

import "fmt"

func main() {
    var newFunc func(int, int) int
    newFunc = func(i int, j int) int {
        return (i * j)
    }

    fmt.Println(newFunc(10, 20))

}

但是,如果我从主函数中取出函数声明部分(如下所示),它将无法编译。是否必须在main()函数中声明它?

package main

import "fmt"

var newFunc func(int, int) int
newFunc = func(i int, j int) int {
    return (i * j)
}

func main() {


    fmt.Println(newFunc(10, 20))

}

编译Err细节如下:

.\functionanonymous1.go:6:1: syntax error: non-declaration statement outside function body
.\functionanonymous1.go:6:15: missing function body
.\functionanonymous1.go:6:33: method has multiple receivers
.\functionanonymous1.go:7:2: syntax error: unexpected return, expecting )
.\functionanonymous1.go:8:1: syntax error: non-declaration statement outside function body
回复
  • baut 回复

    A go program with short variable declarations outside a function doesn’t compile. You may have noticed that from the error logs, syntax error: non-declaration statement outside function body.

    package main
    
    var a int
    
    a = 1 // illegal
    b := 1 // illegal
    
    var c = 1 // legal
    
    func main() {}
    

    更新的代码:

    package main
    
    import "fmt"
    
    var newFunc = func(i int, j int) int {
        return (i * j)
    }
    
    func main() {
    
        fmt.Println(newFunc(10, 20))
    
    }
    

    Go Playground

  • Simply, golang doesn't allow that. A variable that declares outside function must contain var.

    因此,您可以尝试:

    package main
    
    import "fmt"
    
    var newFunc func(int, int) int = func(i int, j int) int {
         return (i * j)
    }
    
    func main() {
         fmt.Println(newFunc(10, 20))
    }