当前位置:网站首页>[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
边栏推荐
猜你喜欢
随机推荐
Postgresql 快照
ES6 Const Let Var的区别
(十)树的基础部分(一)
flink-sql所有表格式format
ISCC2021——web部分
iptables防火墙
Commons Collections1
TensorFlow:tf.ConfigProto()与Session
postgresql 游标(cursor)的使用
关系型数据库-MySQL:约束管理、索引管理、键管理语句
sklearn中的pipeline机制
Shell(2)数值运算与判断
(十六)图的基本操作---两种遍历
浏览器中的同源策略
关系型数据库-MySQL:二进制日志(binlog)
视图、存储过程、触发器
Lombok的一些使用心得
flink onTimer定时器实现定时需求
剑指 Offer 20226/30
(十五)B-Tree树(B-树)与B+树