dongrandi8411 2019-09-05 23:34
浏览 92

从函数返回函数,为什么省略括号?

I am currently in UCI Go Lang Course and Came across this function which the Syntax I did not understand. The function is directly from the example code, but has a syntax error I do not understand line 2 bracket. Also I come from JS, and C and Why in go are some functions declared without outer brackets?

 func MakeDistOrigin(o_x, o_y float64)
            func (float64, float64) float64 {
   fn := func (x, y float64) float64 {
            return math.Sqrt(math.Pow(x - o_x, 2) + 
                      math.Pow(y - o_y, 2))
         }
   return fn
    }

I expected this function to have outer brackets for each function and to return a function that then takes in another variable. Thanks!

  • 写回答

1条回答 默认 最新

  • dongpingwu8378 2019-09-05 23:45
    关注

    If you got a syntax error, probably you have a newline after func MakeDistOrigin(o_x, o_y float64). Move the func (float64, float64) float64 { to the same line as the MakeDistOrigin declaration, and it should be good.

    The second line in the code you pasted is not a function declaration. It is the return type of MakeDistOrigin. Look at it this way:

    func MakeDistOrigin(o_x, o_y float64) T {
    }
    

    In the above declaration, T is the following type:

    func (float64, float64) float64 
    

    So in fact you can simplify this declaration by:

    type T func (float64, float64) float64 
    
    func MakeDistOrigin(o_x, o_y float64) T {
    }
    

    So MakeDistOrigin is a function that returns a function of type T, which is a function that gets two float64 values and returns a float64 value.

    Inside MakeDistOrigin, a variable fn is declared. This variable is of type T as well, that is a function that takes two float64s and returns one.

    The variable fn is initialized with the function definition given next to it, which is, again, a function of type T.

    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划