当前位置:网站首页>学习 Go 语言 0x03:理解变量之间的依赖以及初始化顺序
学习 Go 语言 0x03:理解变量之间的依赖以及初始化顺序
2022-04-23 11:02:00 【爱博客大伯】
本文介绍 Go 语言中变量之间的依赖,也是 Go 语言规范中的例子,只是扩充了一点点。
* 代码
package main
import "fmt"
var (
a = b + c
b = f()
c = f()
d = 3
)
func f() int {
d++
return d
}
func main() {
fmt.Printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d)
}
你可以凭直觉,想一想输出结果是什么。
先
思
考
一
下
。
。
。
输出结果是,a = 9, b = 4, c = 5, d = 5,你做对了吗?
从这段代码来看:
var (
a = b + c
b = f()
c = f()
d = 3
)
func f() int {
d++
return d
}
a依赖b和cb依赖dc依赖d
所以,初始化顺序为d,b,c,a.
这种依赖关系可以画成一棵树,从树的叶子结点开始初始化,直到树的根结点。
在打印的时候,会以类似树的后续遍历的方式来初始化。
例如,打印a时,需要计算a,计算a时,需要先计算b和c。
计算b时,需要计算d,然后执行d的初始化d=3,此时d为3。
然后就可以计算 b了 ,执行f(),此时d为4,所以,b为4 。
然后计算 c ,执行f(),此时 d为5,所以,c为5 。
然后计算a,a=4+5,所以 a为9 。
所以打印结果为:a = 9, b = 4, c = 5, d = 5
* 参考
版权声明
本文为[爱博客大伯]所创,转载请带上原文链接,感谢
https://blog.csdn.net/u013553529/article/details/88903381
边栏推荐
- CUMCM 2021-B:乙醇偶合制备C4烯烃(2)
- Facing the global market, platefarm today logs in to four major global platforms such as Huobi
- ffmpeg命令行常用参数
- SQL Server cursor circular table data
- 面向全球市场,PlatoFarm今日登录HUOBI等全球四大平台
- Visual common drawing (III) area map
- 使用zerotier让异地设备组局域网
- Common parameters of ffmpeg command line
- Ueditor -- limitation of 4m size of image upload component
- Wonderful review | deepnova x iceberg meetup online "building a real-time data Lake based on iceberg"
猜你喜欢

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

The songbird document editor will be open source: starting with but not limited to markdown

MySQL Router重装后重新连接集群进行引导出现的——此主机中之前已配置过的问题

Charles function introduction and use tutorial

【leetcode】102. Sequence traversal of binary tree

The courses bought at a high price are open! PHPer data sharing

Intuitive understanding entropy

Mysql8. 0 installation guide

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

【leetcode】107. Sequence traversal of binary tree II
随机推荐
Ueditor -- limitation of 4m size of image upload component
【leetcode】199. Right view of binary tree
colab
About the three commonly used auxiliary classes of JUC
Qinglong panel pull library command update [April 20, 2022] collection is not lost
数据库管理软件SQLPro for SQLite for Mac 2022.30
ID number verification system based on visual structure - Raspberry implementation
STM32接电机驱动,杜邦线供电,然后反烧问题
remote: Support for password authentication was removed on August 13, 2021.
语雀文档编辑器将开源:始于但不止于Markdown
Esp32 learning - use and configuration of GPIO
Difference between pregnancy box and delivery box
Diary of dishes | Blue Bridge Cup - hexadecimal to octal (hand torn version) with hexadecimal conversion notes
Alarm scene recognition
Solution architect's small bag - 5 types of architecture diagrams
全栈交叉编译X86完成过程经验分享
vm设置静态虚拟机
软件测试人员,如何优秀的提Bug?
Microsoft Access database using PHP PDO ODBC sample
CUMCM 2021-B:乙醇偶合制備C4烯烴(2)