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!
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
.