当前位置:网站首页>[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
边栏推荐
猜你喜欢
随机推荐
剑指 Offer 2022/7/12
postgresql 事务隔离级别与锁
flink-sql所有数据类型
攻防世界MISC—MISCall
关系型数据库-MySQL:多实例配置
逻辑回归---简介、API简介、案例:癌症分类预测、分类评估法以及ROC曲线和AUC指标
(TensorFlow)——tf.variable_scope和tf.name_scope详解
NFT市场开源系统
纳米级完全删除MYSQL5.7以及一些吐槽
安卓连接mysql数据库,使用okhttp
Kubernetes基本入门-集群资源(二)
flink onTimer定时器实现定时需求
【深度学习21天学习挑战赛】备忘篇:我们的神经网模型到底长啥样?——model.summary()详解
sklearn中的学习曲线learning_curve函数
ES6 Const Let Var的区别
k3s-轻量级Kubernetes
(六)递归
智能合约安全——私有数据访问
Th in thymeleaf: href use notes
Kubernetes基础入门(完整版)









