当前位置:网站首页>Go变量的声明与赋值
Go变量的声明与赋值
2022-06-26 13:57:00 【m0_52339560】
Go变量的声明与赋值
声明变量的三种形式
var 变量名 变量类型
示例:
var name int = 0 //声明了一个int型的变量,其标识符为name println(int)
var 变量名
:通过声明变量类型来声明变量,编译器会通过初始化的值来自行推断变量类型。
示例:省略了变量类型,那么必须在声明时给定初值,能够让编译器判断其类型,否则语法错
missing variable type or initializationsyntax
。var name = 0 var name1 = "Hello go" println(name, name1) //输出为0 Hello go print(fmt.Sprintf("%T---%T", name, name1))//打印两个变量的类型 //int---string name为int型,name1为string型
- 使用
:=
声明变量并赋初值
示例:
name := "Hello go" println(name)
上述代码等价于:
var name string name = "Hello go" println(name)
注意:使用
:=
相当于声明变量和为变量初始化同时进行,所以对于表达式name:="Hello go"
,如果变量name
此前已经声明过,则不允许再次声明。如果声明,则语法检测器会显示错误no new variables on left side of :=
。
多变量声明
如果同时要声明多个相同类型的变量,可以采用如下型式:
var name1, name2, name3 int = 1, 2, 3
如果要同时声明多个相同或不同类型的变量,则可以采用如下形式:
var name1, name2, name3 = 123, 2.0, "Hello go"
赋值时,等号右侧的多个数值或字符串根据它们的相对位置,依次赋值给等号左侧的变量
全局变量的声明
声明全局变量依然可以使用之前介绍的三种变量声明的方法。这里介绍全局变量声明的另外一种写法:
var(
name1 int
name2 string
name3 float32
)
局部变量的注意事项
对于局部变量,其声明在函数体内,一旦被声明,那么它必须在后面的代码段中被使用,否则会出现编译错。
而对于全局变量,它可以被声明而不被使用。
标识符_
对于表示符_
,常用来抛弃不需要的值。比如函数func
返回两个值a, b
,不需要b
的值,那么可以这样写:
a, _ = func()
与python
的_
类似。但是Go
中的_
不能够被读取,只能向该变量中写入值。而在python
中,可以读取_
中的值。
参考资料
- https://www.runoob.com/go/go-variables.html
边栏推荐
- One article of the quantification framework backtrader read observer
- Sharing ideas for a quick switch to an underlying implementation
- 《三体》摘录
- 通俗语言说BM3D
- Deploy the flask environment using the pagoda panel
- Correlation analysis related knowledge
- 国信证券的排名如何?办理股票开户安全吗?
- Installation tutorial about origin2019
- Practice with the topic of bit operation force deduction
- Stream常用操作以及原理探索
猜你喜欢
Build your own PE manually from winpe of ADK
印尼投资部长:鸿海考虑在其新首都建立电动公交系统、城市物联网
Common evaluation indexes of classification model -- confusion matrix and ROC curve
Codeforces Global Round 21A~D
Sword finger offer 10 Ⅰ 10Ⅱ. 63 dynamic planning (simple)
PostGIS create spatial database
Sword finger offer 06.24.35 Linked list
Combat readiness mathematical modeling 31 data interpolation and curve fitting 3
这才是优美的文件系统挂载方式,亲测有效
Hard (magnetic) disk (I)
随机推荐
PostGIS create spatial database
K gold Chef (two conditions, two points and difference)
Difference between classification and regression
Sword finger offer 10 Ⅰ 10Ⅱ. 63 dynamic planning (simple)
Freefilesync folder comparison and synchronization software
Complete diagram / Euler loop
GDAL grid data types and their type codes
ArcGIS cannot be opened and displays' because afcore cannot be found ' DLL, solution to 'unable to execute code'
Practical website recommendations worth collecting for College Students
从Celsius到三箭:加密百亿巨头们的多米诺,史诗级流动性的枯竭
在云服务器中云磁盘如何挂载
通俗语言说BM3D
在线牛人博主
Hard (magnetic) disk (II)
The engine "node" is inconsistent with this module
Two dimensional DFS
工作上对金额价格类小数点的总结以及坑
SwiftUI找回丢失的列表视图(List)动画
【async/await】--异步编程最终解决方案
JVM 输出 GC 日志导致 JVM 卡住,我 TM 人傻了