当前位置:网站首页>Go language pointer
Go language pointer
2022-07-17 23:28:00 【tiwayDeng】
What is a pointer
The pointer is a variable , Its value is the address of another variable , That is, the direct address of the memory location . Like variables or constants , You must declare a pointer first , Then you can use it to store any variable address .
The general form of pointer variable declaration is :
var var-name *var-type
here ,var-type Is the base type of the pointer ; It has to be effective Go data type ,var-name Is the name of the pointer variable . The asterisk used to declare the pointer (*) Same as the asterisk used for multiplication .
however , In this statement , asterisk (*) Used to specify variables as pointers . Here is a valid pointer declaration :
var ip *int // Pointer to an integer
var fp *float32 // Point to floating point pointer
The actual data type of the value of all pointers ( Whether it's an integer , Floating point number or other data types ) It's all the same , It represents the long hexadecimal number of the memory address .
The only difference between pointers of different data types is that the pointer points to the data type of variable or constant .
How to use the pointer
Each variable is a memory location , Each memory location has its defined address , have access to ” and ” Number (&) Operator to access it , This operator represents the address in memory . Refer to the following example , It will print the address of the defined variable :
package main
import "fmt"
func main() {
var a int = 10
fmt.Printf("Address of a variable: %x\n", &a )
}
This is done by using the unary operator * To return the value of the variable at the address specified by the operand . The following example uses these operations :
package main
import "fmt"
func main() {
var a int= 20
var ip *int
ip = &a
fmt.Printf("a Memory address : %x\n", &a )
fmt.Printf("ip Memory address : %x\n", ip )
fmt.Printf("*ip value : %d\n", *ip )
}
When the above code is compiled and executed , It produces the following results :
a Memory address : 10328000
ip Memory address : 10328000
*ip value : 20
Nil The pointer
stay Go In language nil The pointer Go The compiler assigns a pointer variable Nil value , In case the pointer doesn't have an exact address assignment . This is done at variable declaration time . Designated as nil The pointer to the value is called nil The pointer .
nil Pointers are constants with a value of zero defined in several standard libraries . Refer to the following procedure :
package main
import "fmt"
func main() {
var ptr *int
fmt.Printf("The value of ptr is : %x\n", ptr )
}
When the above code is compiled and executed , It produces the following results :
The value of ptr is 0
On most operating systems , The program does not allow access to addresses 0 Memory at , Because this memory is reserved by the operating system .
However , Memory address 0 Of special significance ; It indicates that the pointer is not intended to point to an accessible memory location . But by convention , If the pointer contains nil( zero ) value , Suppose it doesn't point to anything .
Check whether it is nil The pointer , have access to if sentence , As shown below :
if(ptr != nil)
if(ptr == nil)
Pointer array
Before understanding the concept of pointer array , Take a look at the following example , It uses a 3 Array of integers :
package main
import "fmt"
const MAX int = 3
func main() {
a := []int{
10,100,200}
var i int
for i = 0; i < MAX; i++ {
fmt.Printf("Value of a[%d] = %d\n", i, a[i] )
}
}
When the above code is compiled and executed , It produces the following results :
Value of a[0] = 10
Value of a[1] = 100
Value of a[2] = 200
There may be a situation , When you want to maintain an array , It can store points int Or a pointer to a string or any other available data type . Here is a declaration of an array of pointers to integers :
var ptr [MAX]*int;
There will be ptr Declare as a MAX Pointer array of integers .
therefore ,ptr Each element in now holds a point int Pointer to value . The following example uses three integers , They will be stored in the pointer array , As shown below :
package main
import "fmt"
const MAX int = 3
func main() {
a := []int{
10,100,200}
var i int
var ptr [MAX]*int;
for i = 0; i < MAX; i++ {
ptr[i] = &a[i]
}
for i = 0; i < MAX; i++ {
fmt.Printf("Value of a[%d] = %d\n", i,*ptr[i] )
}
}
When the above code is compiled and executed , It produces the following results :
Value of a[0] = 10
Value of a[1] = 100
Value of a[2] = 200
Pointer passed to function
Go Programming languages allow you to pass a pointer into a function .
So , Just declare the parameters of the function as pointer types . Take a look at the following simple example , Passed two pointers to a function , And change their values in the function , This value is reflected in the calling function :
package main
import "fmt"
func main() {
var a int = 100
var b int= 200
fmt.Printf(" Before function change a : %d\n", a )
fmt.Printf(" Before function change b : %d\n", b )
// Pass the pointer address into the function
swappr(&a, &b);
fmt.Printf(" After the transmission pointer address changes a : %d\n", a )
fmt.Printf(" After the transmission pointer address changes b : %d\n", b )
swapval(a, b);
fmt.Printf(" After passing the value a : %d\n", a )
fmt.Printf(" After passing the value b : %d\n", b )
}
func swappr(x *int, y *int) {
var temp int
temp = *x
*x = *y
*y = temp
}
func swapval(x int, y int) {
var temp int
temp = x
x = y
y = temp
}
When the above code is compiled and executed , It produces the following results :
Before function change a : 100
Before function change b : 200
After the transmission pointer address changes a : 200
After the transmission pointer address changes b : 100
After passing the value a : 200
After passing the value b : 100
The pointer of the pointer
Pointers to pointers are multiple indirect forms or chains of pointers . Usually , The pointer contains the address of the variable . When defining a pointer to a pointer , The first pointer contains the address of the second pointer , It points to the location containing the actual value , As shown below .
Variables that are pointers to pointers must be declared like this . This is done by adding an asterisk in front of its name (*) To achieve . for example , Here is a point int Declaration of pointer to type :
var ptr **int;
When the target value is indirectly pointed by the pointer to the pointer , To access this value, you need to apply two asterisks (**) Operator , As the following example shows :
package main
import "fmt"
func main() {
var a int
var ptr *int
var pptr **int
a = 3000
ptr = &a
pptr = &ptr
/* take the value using pptr */
fmt.Printf("Value of a = %d\n", a )
fmt.Printf("Value available at *ptr = %d\n", *ptr )
fmt.Printf("Value available at **pptr = %d\n", **pptr)
}
When the above code is compiled and executed , It produces the following results :
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
Summary
Go The pointer in is easy to learn , It's also more interesting . some Go Programming tasks are easier to perform with pointers , And you can't perform other tasks without using pointers , For example, modify the value of variables by passing in references
边栏推荐
- Shadow plug-in framework design -- replugin principle (Advanced journey of Architects)
- The whole process of easy gene chromatin immunoprecipitation sequencing (chip SEQ) analysis experiment
- 速卖通关键词搜索商品API接口(item_search-按关键字搜索aliexpress商品接口)
- 小红书商品详情API接口(item_get-获得小红书商品详情接口)
- 15.1.1、MySQL—mysql的日期时间函数,日期格式化
- OSPF experiment in mGRE environment
- 淘宝app商品详情API接口(商品详情描述信息查询接口)
- Sword finger offer 06 Print linked list from end to end
- Shadow插件化框架设计——replugin原理(架构师进阶之旅)
- 洽洽陈先保,六旬老汉复出,他还能折腾多少?
猜你喜欢

Session tracking technology cookies and sessions

On volatile

一个八年软件测试工程师之路

1688 API interface for all goods in the store (API interface for querying all goods in the whole store)

An eight year road of Software Testing Engineer

Proxmox ve 7.2 LxC deployment openwrt

YOLO系列论文精度 & YOLOv2 and YOLO9000

VMware Photon OS 4 Install

Week 4 Data analysis algorithms-Linear models for regression-Bias-Variance Analysis(Part B)

hyper子查询优雅实现join查询
随机推荐
Application scheme for remote monitoring of Wutong Bolian photovoltaic power station
Array parameter, pointer parameter, function pointer, function pointer array of C language
How long does a tester insist on changing jobs in order to improve his salary perfectly?
《微信小程序-进阶篇》package.json版本说明及各类版本符号详解(一)
Unity 判断物体是否在相机前面以及UI跟随3D物体
秒杀项目学习
conda安装包速度太慢(以torch为例)
区别go array,slice,map
C语言中的关键字struct、union、enum、typedef
ZABBIX fault set -- when you forget the account and password to log in to ZABBIX system
[untitled]
There are surprises when opening
The problem of idea configuring NPM to jump to 0.0.0.0 after startup is solved
PolarDB for PostgreSQL结合Ceph共享存储的结构图是怎样的?
几行汇编几行C实现一个最简单的内核
剑指 Offer 06. 从尾到头打印链表
Implementation of wechat applet Netease cloud music cloud music
Interviewer: how to clean the data of ES cluster regularly
C#中的Explicit和Implicit了解一下吧
R language uses circular statements to draw multiple pictures at one time