当前位置:网站首页>【Yugong Series】July 2022 Go Teaching Course 013-Constants, Pointers
【Yugong Series】July 2022 Go Teaching Course 013-Constants, Pointers
2022-07-31 00:23:00 【HUAWEI CLOUD】
一、常量
1.常量的定义
常量是一个简单值的标识符,在程序运行时,不会被修改的量.
常量中的数据类型只可以是布尔型、数字型(整数型、浮点型和复数)和字符串型.
常量的定义格式:
const identifier [type] = value
你可以省略类型说明符 [type],因为编译器可以根据变量的值来推断其类型.
定义一个 Go 语言常量非常简单,它和变量的声明方式类似,将 var 关键字替换成 const 即可,代码如下:
const pi = 3.141592const name = "愚公搬代码"
2.常量的使用
package mainimport ( "fmt")const ( pi = 3.141592 name = "愚公搬代码")func main() { fmt.Println(pi, name)}
二、指针
1.指针的定义
在计算机中,所有的数据都是存放在存储器中的,不同的数据类型占有的内存空间的大小各不相同.内存是以字节为单位的连续编址空间,每一个字节单元对应着一个独一的编号,这个编号被称为内存单元的地址.比如:int 类型占 4 个字节,char 类型占 1 个字节等.系统在内存中,为变量分配存储空间的首个字节单元的地址,称之为该变量的地址.地址用来标识每一个存储单元,方便用户对存储单元中的数据进行正确的访问.在高级语言中地址形象地称为指针.
2.指针的使用
每个变量在程序运行时都有一个地址,这个地址代表变量在内存中的位置.
Go 语言中,通过 & 操作符对变量进行 “取地址” 操作,格式如下:
p := &v // v 的类型为 T
上面代码中,v 表示被取地址的变量,取到的地址用变量 p 进行接收, p 的类型为 “*T”, 称为 T 的指针类型.*代表指针.
案例如下:
package mainimport "fmt"func main() { var name string = "愚公搬代码" // 获取字符串的指针, p 类型为*string p := &name // 打印变量 p 的类型 fmt.Printf("p type: %T\n", p) // 打印变量 p 的指针地址 fmt.Printf("address: %p\n", p) // 通过 * 对指针进行取值操作 value := *p // 取值后的类型 fmt.Printf("value type: %T\n", value) // 指针取值后指向变量的值 fmt.Printf("value type: %s\n", value)}
- &, 取地址操作符,功能是取出变量在内存中的地址;
- *,取值操作符,功能是取出地址指向的实际值.
边栏推荐
- Steven Giesel recently published a 5-part series documenting his first experience building an application with the Uno Platform.
- How to solve the error of joiplay simulator
- MySQL数据库的truncate与delete区别
- h264和h265解码上的区别
- A Brief Talk About MPI
- Android security optimization - APP reinforcement
- 【愚公系列】2022年07月 Go教学课程 016-运算符之逻辑运算符和其他运算符
- IOT跨平台组件设计方案
- 正则表达式密码策略与正则回溯机制绕过
- 【深度学习】Transformer模型详解
猜你喜欢
Machine Learning 1-Regression Model (2)
在微服务中使用事件溯源的六大原因 - Herath
C语言力扣第48题之旋转图像。辅助数组
牛客网刷题训练(四)
[In-depth and easy-to-follow FPGA learning 15---------- Timing analysis basics]
【深入浅出玩转FPGA学习14----------测试用例设计2】
Error occurred while trying to proxy request项目突然起不来了
How to solve the error of joiplay simulator
Jmeter参数传递方式(token传递,接口关联等)
Neural Network (ANN)
随机推荐
牛客网刷题训练(四)
Go 学习笔记(84)— Go 项目目录结构
How to ensure the consistency of database and cache data?
[In-depth and easy-to-follow FPGA learning 13---------Test case design 1]
MySQL中substring与substr区别
MPI简谈
joiplay模拟器不支持此游戏类型怎么解决
45. [Application of list linked list]
MySQL笔记下
@requestmapping注解的作用及用法
Xss target drone training [success when pop-up window is realized]
what is jira
(5) fastai application
mysql索引失效的常见9种原因详解
(五)fastai应用
IOT cross-platform component design scheme
A Brief Talk About MPI
.NET 跨平台应用开发动手教程 |用 Uno Platform 构建一个 Kanban-style Todo App
pytorch bilinear interpolation
Android security optimization - APP reinforcement