du21064 2017-03-24 15:04
浏览 235

golang:隐式vs显式func定义

Consider this package:

package A
var X="change me"
var Y=func(i int) int { return i*i) }
func Z(i int) int { return -i) }

The two explicit variables (X,Y) can be changed in another package, say main...

package main
import "A"
func main () {
    A.X="done"
    A.Y=func (i int) int { return i*i*i }
    print(A.X,A.Y(7))
    //... but A.Z apparently can't be changed.
    //A.Z=func (int i) int { return i*i*i } //main.go:8: cannot assign to A.Z
}

Obviously there's a difference between defining a func variable (like Y) and an explicit func (like Z). I have googled this but not found much in the way of enlightenment. It almost seems as if var SomeFunc=func (...) defines indeed a variable, but func SomeFunc(...) defines a constant.

PS: A small goodie I found while researching this which I have not seen mentioned in the Go books I've read so far. A dot before a package import imports names without them having to be qualified:

package main
import . "A"
func main () {
    X="done"
    Y=func (i int) int { return i*i*i }
    print(X,Y(7))
}
  • 写回答

2条回答 默认 最新

  • dqwr32867 2017-03-24 15:09
    关注

    There's a difference between declaring a variable initialized with a function value:

    var Y=func(i int) int { return i*i) }
    

    and declaring a function:

     func Z(i int) int { return -i) }
    

    The specification says this about declarations:

    A declaration binds a non-blank identifier to a constant, type, variable, function, label, or package.

    The specification also says:

    A function declaration binds an identifier, the function name, to a function.

    The declaration of Y binds a variable to the name. This variable is initialized with a function value. The declaration of Z binds a function to the name.

    If an explicit period (.) appears instead of a name, all the package's exported identifiers declared in that package's package block will be declared in the importing source file's file block and must be accessed without a qualifier.

    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能