当前位置:网站首页>[Introduction to go language] 12. Pointer
[Introduction to go language] 12. Pointer
2022-08-04 06:05:00 【Live up to [email protected]】
指针is a representative of a certain内存地址的值
说到指针,will make many people“谈虎色变”,Especially for pointer offsets、运算、Conversions are very scary.
其实,pointer isC/C++Languages have extremely high performance fundamentals,Convenient and convenient when manipulating large blocks of data and doing offsets.
C/C++The root cause of the criticism of pointers in China is pointer arithmetic and memory freeing.
C/C++Raw pointers in the language can be freely offset,It can even be offset into the operating system core area in some cases.
Our computer operating systems often need to be updated、Fix the nature of the vulnerability,It is caused by out-of-bounds access to the pointer“缓冲区溢出”.
指针概念在Go语言中被拆分为两个核心概念:
- 类型指针:allowed for this pointer type数据进行修改.传递数据使用指针,而无须拷贝数据.类型指针不能进行偏移和运算.
- 切片,by pointing to the starting element原始指针、元素数量和容量组成.
受益于这样的约束和拆分,Go语言的指针类型变量拥有指针的高效访问,但又不会发生指针偏移,从而避免非法修改关键性数据问题.同时,垃圾回收也比较容易对不会发生偏移的指针进行检索和回收.
1 、Recognize pointer addresses、指针类型
每个变量在运行时都拥有一个地址,这个地址代表变量在内存中的位置.
Go语言中使用&operator is placed变量前面对变量进行“取地址”操作.
格式如下:p := &变量
例:
package main
import (
"fmt"
)
func main() {
a := "hello"
p := &a //用符号 & 取变量a的地址
fmt.Println(p)
}
运行结果:
注:
- 输出了变量a的内存地址
- 输出值在每次运行是不同的
- 在32位平台上,将是32位地址;64位平台上是64位地址.
2、 从指针获取指针指向的值
在对普通变量使用&操作符取地址获得这个变量的指针后
可以对指针使用*操作,也就是指针取值
例:
package main
import (
"fmt"
)
func main() {
a := "hello"
p := &a
fmt.Println(p) //输出a的地址,p指针变量
fmt.Println(*p) //输出a的地址存储的值
}
运行结果:
3、使用指针修改值

package main
import (
"fmt"
)
func main() {
a := "hello" //变量a
p := &a //p指向a变量地址
b := "hello world" //变量b
*p = b //修改指针pThe content of the memory pointed to changes
fmt.Println(a) //输出a的地址存储的值
}
运行结果:
4、new()函数创建指针
语法:指针变量 := new(数据类型)
例:
package main
import (
"fmt"
)
func main() {
c := new(string)
*c = "hello world"
fmt.Println(*c)
}
运行结果:
版权声明
本文为[Live up to [email protected]]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/216/202208040525327344.html
边栏推荐
猜你喜欢
随机推荐
二月、三月校招面试复盘总结(一)
【深度学习21天学习挑战赛】备忘篇:我们的神经网模型到底长啥样?——model.summary()详解
自动化运维工具Ansible(4)变量
自动化运维工具Ansible(3)PlayBook
字典特征提取,文本特征提取。
postgresql中创建新用户等各种命令
关系型数据库-MySQL:多实例配置
数据库根据提纲复习
TensorFlow2学习笔记:6、过拟合和欠拟合,及其缓解方案
PostgreSQL模式(Schema)
Androd Day02
thymeleaf中 th:href使用笔记
彻底搞懂箱形图分析
Kubernetes基本入门-元数据资源(四)
EPSON RC+ 7.0 使用记录一
安卓连接mysql数据库,使用okhttp
flink-sql所有数据类型
对象存储-分布式文件系统-MinIO-2:服务端部署
剑指 Offer 2022/7/2
MySQL事务详解(事务隔离级别、实现、MVCC、幻读问题)








![[NSSRound#1 Basic]](/img/0a/b2fc70947e3c76178d2faa86a1085d.png)
