当前位置:网站首页>【愚公系列】2022年7月 Go教学课程 005-变量
【愚公系列】2022年7月 Go教学课程 005-变量
2022-07-07 12:35: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=10
num=20
fmt.Println(age,num) //10,20
将一个变量赋值给另一个变量如下:
var age int =10
var num int
num=age
fmt.Println(num) //10
注意:变量进行赋值会覆盖原有的旧值
3.4 案例:交换两个变量的值
临时变量
package main
import "fmt"
func main(){
a := 1
b := 5
var t int
t = a
a = b
b = t
fmt.Println("a = ", a, "b = ", b )
}
不使用临时变量
package main
import "fmt"
func main(){
a := 1
b := 5
a = a + b
b = a - b
a = a - b
fmt.Println("a = ", a, "b = ", b )
}
直接赋值
package main
import "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函数,中间用英文半角逗号进行分割!
- 可以将一个变量的值,赋值给另外一个变量,并且变量中原有的旧值被新值所覆盖。
边栏推荐
猜你喜欢

Redis 核心数据结构 & Redis 6 新特性详

GAN发明者Ian Goodfellow正式加入DeepMind,任Research Scientist

libSGM的horizontal_path_aggregation程序解读

AI talent cultivation new ideas, this live broadcast has what you care about

Flask session forged hctf admin

Reverse non return to zero code, Manchester code and differential Manchester code of common digital signal coding

MRS离线数据分析:通过Flink作业处理OBS数据
![GVIM [III] [u vimrc configuration]](/img/82/38355d7914e5fe490546347e57e35d.png)
GVIM [III] [u vimrc configuration]

常用数字信号编码之反向不归零码码、曼彻斯特编码、差分曼彻斯特编码

Docker deploy Oracle
随机推荐
How to check the ram and ROM usage of MCU through Keil
The longest ascending subsequence model acwing 1014 Mountaineering
Vscode configuration uses pylint syntax checker
NDK beginner's study (1)
Cargo placement problem
请问,PTS对数据库压测有好方案么?
Cesium 已知一点经纬度和距离求另一个点的经纬度
Excuse me, why is it that there are no consumption messages in redis and they are all piled up in redis? Cerely is used.
Leetcode——236. The nearest common ancestor of binary tree
Leetcode——236. 二叉树的最近公共祖先
一个简单LEGv8处理器的Verilog实现【四】【单周期实现基础知识及模块设计讲解】
PERT图(工程网络图)
Cesium knows the longitude and latitude of one point and the distance to find the longitude and latitude of another point
LeetCode 648. 单词替换
Parsing of XML files
When FC connects to the database, do you have to use a custom domain name to access it outside?
Beginner XML
Lavarel之环境配置 .env
多商户商城系统功能拆解01讲-产品架构
call undefined function openssl_cipher_iv_length