Skip to content

Instantly share code, notes, and snippets.

@AGou-ops
Last active January 26, 2022 06:28
Show Gist options
  • Save AGou-ops/3137d3a8d8cd5e8c34c6bc13cadd6252 to your computer and use it in GitHub Desktop.
Save AGou-ops/3137d3a8d8cd5e8c34c6bc13cadd6252 to your computer and use it in GitHub Desktop.
斐波那契数列两种闭包实现&为字符串添加后缀的闭包工厂函数
package main
import (
"fmt"
"strings"
"time"
)
// 斐波那契数列实现1
func fibonacci() func(int) int {
return func(i int) int {
switch i {
case 0:
return 0
case 1, 2:
return 1
default:
return fibonacci()(i-1) + fibonacci()(i-2)
}
}
}
// 斐波那契梳理实现2
func fibonacci1() func() int {
var a, b int = 1, 0
return func() int {
a, b = b, a+b
return b
}
}
func main() {
start := time.Now()
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f(i))
}
end := time.Now()
fmt.Println("fibonacci() func Time: ", end.Sub(start))
fmt.Println(strings.Repeat("*", 100))
start = time.Now()
f1 := fibonacci1()
for i := 0; i < 10; i++ {
fmt.Println(f1())
}
end = time.Now()
fmt.Println("fibonacci1() func Time: ", end.Sub(start))
fmt.Println(strings.Repeat("*", 100))
// 可以返回其它函数的函数和接受其它函数作为参数的函数均被称之为高阶函数
addJPG := addExtensions(".jpg")
fmt.Println(addJPG("hello"))
}
// 一个返回值为另一个函数的函数可以被称之为工厂函数
func addExtensions(suffix string) func(str string) string {
return func(name string) string {
if suffix == "" {
return "no suffix"
}
if !strings.HasSuffix(name, suffix) {
return name + suffix
}
return name
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment