当前位置:网站首页>【愚公系列】2022年7月 Go教学课程 005-变量
【愚公系列】2022年7月 Go教学课程 005-变量
2022-07-07 09:21:00 【华为云】
一、变量
1.变量的定义
变量来源于数学,用于描述计算机中的数据存储空间。变量可以通过变量名访问。在指令式语言中,变量通常是可变的;但在纯函数式语言(如Haskell)中,变量可能是不可变(immutable)的。在一些语言中,变量可能被明确为是能表示可变状态、具有存储空间的抽象(如在Java和Visual Basic中);但另外一些语言可能使用其它概念(如C的对象)来指称这种抽象,而不严格地定义“变量”的准确外延。
2.变量的作用
变量的作用就是在内存中标记和存储数据。
内存,全称内存储器。用于存放计算机运行过程中的数据。
计算机为了更好的存储数据,将内存分为不同的存储单元如下:
从内存中取出一个存储单元,存储相应的数据:
比如上述红色区域,变量名=区域的名字,数据就存在区域中
3.变量的声明和初始化
3.1 变量的声明
Go 是静态语言,所有变量在使用前必须先进行声明。声明的意义在于告诉编译器该变量可以操作的内存的边界信息,而这种边界通常又是由变量的类型信息提供的。在 Go 语言中,有一个通用的变量声明方法是这样的:
变量的使用
fmt.Println(a)3.2 变量的初始化
在定义变量的时候可以赋值,这个过程称为变量初始化
var age int=10
3.3 变量的赋值
可以在变量定义完成之后再给变量赋值,先声明后赋值。
var age,num int age=10num=20fmt.Println(age,num) //10,20将一个变量赋值给另一个变量如下:
var age int =10var num intnum=agefmt.Println(num) //10注意:变量进行赋值会覆盖原有的旧值
3.4 案例:交换两个变量的值
临时变量
package mainimport "fmt"func main(){ a := 1 b := 5 var t int t = a a = b b = t fmt.Println("a = ", a, "b = ", b )}不使用临时变量
package mainimport "fmt"func main(){ a := 1 b := 5 a = a + b b = a - b a = a - b fmt.Println("a = ", a, "b = ", b )}直接赋值
package mainimport "fmt"func main() { a := []int{1, 2} b := []int{3, 4, 5} a, b = b, a fmt.Println(`a:`, a) fmt.Println(`b:`, b)}总结
- 变量声明:var变量名称变量类型
- 声明多个变量:var变量名称1,变量名称…类型
- 声明整型变量,默认值为0
- 输出语句可以只使用一个Println函数,中间用英文半角逗号进行分割!
- 可以将一个变量的值,赋值给另外一个变量,并且变量中原有的旧值被新值所覆盖。
边栏推荐
- [untitled]
- Table replication in PostgreSQL
- Kitex 重试机制
- Go Slice 比较
- Debezium同步之Debezium架构详解
- The concept, implementation and analysis of binary search tree (BST)
- Android 面试知识点
- [untitled]
- Which securities company is the best and safest to open an account for the subscription of new shares
- shardingsphere分库分表示例(逻辑表,真实表,绑定表,广播表,单表)
猜你喜欢
随机推荐
Verilog realizes nixie tube display driver [with source code]
electron添加SQLite数据库
[untitled]
Laya common script commands
Vscode 尝试在目标目录创建文件时发生一个错误:拒绝访问【已解决】
After the uniapp jumps to the page in onlaunch, click the event failure solution
【C#】WinForm运行缩放(变糊)的解决方法
Input type= "password" how to solve the problem of password automatically brought in
Debezium同步之Debezium架构详解
自律,提升自制力原来也有方法
Process control (creation, termination, waiting, program replacement)
关于在云服务器上(这里用腾讯云)安装mysql8.0并使本地可以远程连接的方法
Rolling puddle Uni_ App (VIII)
Avoid mutating a prop directly since the value will be overwritten whenever the parent component
Cmake learning manual
Static semantic check of clang tidy in cicd
‘module‘ object is not callable错误
LeetCode - 面试题17.24 最大子矩阵
The use of list and Its Simulation Implementation
oracle常见锁表处理方式
![[untitled]](/img/f9/18b85ad17d4c560f2b9d95a53ee72a.jpg)






![[untitled]](/img/8e/e968d4629004bb0c3ee70328b6777b.jpg)

