Function Closure
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
f2, f1 := 0, 1
// return a function
return func() int {
f := f2
f2, f1 = f1, f+f1
return f
}
}
func main() {
f := fibonacci() // assign
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
Methods
A method is just a function with a receiver argument.
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
// (v Vertex) is a receiver
You can only declare a method with a receiver whose type is defined in the same package as the method. You cannot declare a method with a receiver whose type is defined in another package (which includes the built-in types such as int
).
You can declare methods with pointer receivers.
func (v *Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
Go interprets the statement v.Scale(5)
as (&v).Scale(5)
since the Scale
method has a pointer receiver.
Variadic Parameter
slice1 := []int{0, 1, 2, 3, 4}
slice2 := []int{55, 66, 77}
fmt.Println(slice1)
slice1 = Append(slice1, slice2...) // The '...' is essential!
fmt.Println(slice1)
- Defining Variadic Functions: When defining a function, the
...
operator allows you to specify that the function can take any number of arguments of a specified type. This is similar to variadic functions in other programming languages like C’sprintf
or Python’s*args
. - Passing Arguments to Variadic Functions: When calling a variadic function, you can use the
...
operator to pass a slice as multiple arguments. TheAppend
function is a variadic function that can take multiple integers as arguments. By writingslice2...
, you are essentially spreading out the elements ofslice2
as individual arguments to theAppend
function.