当前位置:网站首页>Learn go language 0x06: Fibonacci closure exercise code in go language journey
Learn go language 0x06: Fibonacci closure exercise code in go language journey
2022-04-23 11:08:00 【Love blog uncle】
* subject
https://tour.go-zh.org/moretypes/26
practice : Fibonacci closure
Achieve one fibonacci function , It returns a function ( Closure ), The closure returns a Fibonacci sequence (0, 1, 1, 2, 3, 5, ...).
* Code
package main
import "fmt"
// Return to one “ return int Function of ”
func fibonacci() func() int {
a := 0
b := 1
return func() int {
ret := a
a = b
b = b + ret
return ret
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
Output :
0
1
1
2
3
5
8
13
21
34
Make minor changes to the code , as follows :
package main
import "fmt"
// Return to one “ return int Function of ”
func fibonacci() func() int {
a := 0
b := 1
return func() int {
ret := a
a, b = b, a + b // Changed here , Updates to the two variables are written on one line
return ret
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
版权声明
本文为[Love blog uncle]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231102105914.html
边栏推荐
- Solutions to common problems in visualization (VIII) solutions to problems in shared drawing area
- 如何使用JDBC CallableStatement.wasNull()方法调用来查看最后一个OUT参数的值是否为 SQL NULL
- How to bind a process to a specified CPU
- 妊娠箱和分娩箱的区别
- SVN的使用:
- web三大组件(Servlet,Filter,Listener)
- Simple thoughts on the design of a microblog database
- Visualized common drawing (II) line chart
- mysql插入datetime类型字段不加单引号插入不成功
- Anaconda3 installation
猜你喜欢

《Neo4j权威指南》简介,求伯君、周鸿袆、胡晓峰、周涛等大咖隆重推荐

数据库管理软件SQLPro for SQLite for Mac 2022.30

Microsoft Access database using PHP PDO ODBC sample

Let the LAN group use the remote device

Structure of C language (Advanced)

STM32接电机驱动,杜邦线供电,然后反烧问题

Ueditor -- limitation of 4m size of image upload component

Visual common drawing (I) stacking diagram

C语言之结构体(进阶篇)

vm设置静态虚拟机
随机推荐
语雀文档编辑器将开源:始于但不止于Markdown
vm设置静态虚拟机
Detailed explanation of integer data type tinyint in MySQL
Detailed explanation of MySQL creation stored procedure and function
mysql分表之后如何平滑上线详解
学习 Go 语言 0x03:理解变量之间的依赖以及初始化顺序
remote: Support for password authentication was removed on August 13, 2021.
关于JUC三大常用辅助类
Mysql系列SQL查询语句书写顺序及执行顺序详解
妊娠箱和分娩箱的区别
Structure of C language (Advanced)
MBA-day5数学-应用题-工程问题
CUMCM 2021-B:乙醇偶合制備C4烯烴(2)
Mysql database transaction example tutorial
Intuitive understanding entropy
一道有趣的阿里面试题
学习 Go 语言 0x02:对切片 Slice 的理解
Visual common drawing (I) stacking diagram
STM32接电机驱动,杜邦线供电,然后反烧问题
Use of SVN: