当前位置:网站首页>[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
边栏推荐
猜你喜欢
随机推荐
NFT市场以及如何打造一个NFT市场
IvNWJVPMLt
组原模拟题
postgres 递归查询
RecyclerView的用法
ES6 Const Let Var的区别
sql中group by的用法
剑指 Offer 2022/7/12
数据库根据提纲复习
Jupyter Notebook安装库;ModuleNotFoundError: No module named ‘plotly‘解决方案。
攻防世界MISC———Dift
ISCC2021——web部分
flink问题整理
编程Go:学习目录
Logistic Regression --- Introduction, API Introduction, Case: Cancer Classification Prediction, Classification Evaluation, and ROC Curve and AUC Metrics
WARNING: sql version 9.2, server version 11.0.Some psql features might not work.
简单明了,数据库设计三大范式
Zend FrameWork RCE1
VScode配置PHP环境
Shell(2)数值运算与判断