Closure functional programming
closure
- Go supports closures
- A closure is a function that has access to variables in the scope of another function. In essence, a closure is a bridge between the inside of a function and the outside of a function.
-
- The purpose of closures is to
- Reads variables inside other functions
- Create a private scope
- The purpose of closures is to
package main
import "fmt"
func addSum(a) func(int) int {
sum := 0
return func(n int) int {
sum = sum + n
fmt.Println(sum + n)
return sum
}
}
type iAddSum func(int) (int,iAddSum)
func addSum2(base int) iAddSum {
return func(i int) (int, iAddSum) {
return base + i, addSum2(base + i)
}
}
func Fibonacci(a) func(a) (old, n int) {
a,b := 1.1
return func(a) (old, n int) {
a,b = b,a+b
return a,b
}
}
func main(a) {
// Data summation
// a :=addSum()
// a :=addSum2(0)
// for i := 0; i < 10; i++ {
// var s int
// s,a = a(i)
// fmt.Println(s)
// }
b := Fibonacci()
for i := 0; i < 10; i++ {
old,n :=b()
fmt.Println(old, n)
}
}
Copy the code
functional
- In Go, functions are first-class citizens. They are variables, types, parameters, return values, and can even implement an interface. However, functions in Go do not support overloading, nesting, and default arguments.
- Features supported by the function
package main
import "fmt"
// as a variable
func test(a){}
funcTest := test
fmt.Println
// Anonymous function
test := func(a){}
// as a type
type iAdder func(int.int) int
func main(a){
var adder iAdder = func(a int, b int) int {
return a + b
}
fmt.Println(adder(1.2)) / / 3
}
// Indeterminate length argument
func test(num ...int){
fmt.Println(num) // [1 2 3 4]
}
test(1.2.3.4)
// Multiple return values
func test(a) (string.int.bool){
return "Hello World".100.true
}
v1, v2, v3 := test()
fmt.Println(v1, v2, v3) // Hello World 100 true
// Name the return value argument
func test(a) (a string, b bool, c int) {
a = "Golang"
b = false
c = 200
return
}
v1, v2, v3 := test()
fmt.Println(v1, v2, v3) // Golang false 200
Copy the code
- Use functions to implement interfaces
package main
import (
"fmt"
"io"
"bufio"
"strings"
)
// Use closures to implement Fibonacci numbers
func fibonacci(a) intGen {
a, b := 0.1
return func(a) int {
a, b = b, a + b
return a
}
}
// Define a type
type intGen func(a) int
// Implement a Reader interface
func (g intGen) Read(p []byte) (n int, err error) {
// Get the next element value
next := g()
if next > 10000 {
return 0, io.EOF
}
// Convert a value to a string
s := fmt.Sprintf("%d/n", next)
return strings.NewReader(s).Read(p)
}
// Use the Reader to read the method
func printFileContents(reader io.Reader){
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
}
func main(a){
f := fibonacci()
printFileContents(f)
}
Copy the code