当前位置:网站首页>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
边栏推荐
- Typora operation skill description (I)
- 学习 Go 语言 0x05:《Go 语言之旅》中映射(map)的练习题代码
- Jupyter Lab 十大高生产力插件
- How to quickly query 10 million pieces of data in MySQL
- Detailed explanation of how to smoothly go online after MySQL table splitting
- 面向全球市场,PlatoFarm今日登录HUOBI等全球四大平台
- 详解MySQL中timestamp和datetime时区问题导致做DTS遇到的坑
- Latex usage
- 《Neo4j权威指南》简介,求伯君、周鸿袆、胡晓峰、周涛等大咖隆重推荐
- Detailed explanation of integer data type tinyint in MySQL
猜你喜欢
Excel·VBA数组冒泡排序函数
Constraintlayout layout
Mysql8.0安装指南
Cygwin 中的 rename 用法
Mysql8. 0 installation guide
Promise details
Google Earth engine (GEE) - scale up the original image (taking Hainan as an example)
初探 Lambda Powertools TypeScript
关于JUC三大常用辅助类
Solutions to common problems in visualization (VIII) solutions to problems in shared drawing area
随机推荐
MySQL partition table can be classified by month
Visualization Road (10) detailed explanation of segmentation canvas function
MySQL索引优化之分页探索详细介绍
Mysql中有关Datetime和Timestamp的使用总结
Excel · VBA custom function to obtain multiple cell values
MBA-day5數學-應用題-工程問題
Ueditor -- limitation of 4m size of image upload component
Xdotool key Wizard
一道有趣的阿里面试题
Mysql系列SQL查询语句书写顺序及执行顺序详解
Typora operation skill description (I)
解决 『SunCertPathBuilderException:unable to find valid certification path to requested target』 问题
比深度学习更值得信赖的模型ART
Implementation of inserting millions of data into MySQL database in 10 seconds
Code implementation of general bubbling, selection, insertion, hill and quick sorting
The songbird document editor will be open source: starting with but not limited to markdown
MBA-day5数学-应用题-工程问题
Differences among restful, soap, RPC, SOA and microservices
MBA-day5数学-应用题-工程问题
Database management software sqlpro for SQLite for Mac 2022.30