Go language does not have pointer arithmetic. The syntax of the go language does not support pointer arithmetic, and all pointers are used within a controllable range; but in fact, the go language can use the Pointer() method of the unsafe package to convert pointers into uintptr type numbers to indirectly Implement pointer arithmetic.

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
What exactly are pointers?
Memory is a series of storage units with serial numbers. Variables are nicknames assigned by the compiler to memory addresses. So what are pointers?
A pointer is a value that points to another memory address variable
The pointer points to the memory address of the variable, and the pointer is like the memory address of the variable value
Let’s look at a code snippet
func main() {
a := 200
b := &a
*b++
fmt.Println(a)
}
In the first line of the main function, we define a new variable a and assign it a value of 200. Next we define a variable b and assign the address of variable a to b. We don't know the exact storage address of a, but we can still store the address of a in the variable b.


Because of the strongly typed nature of Go, the third line of code may be the most disturbing, b contains a The address of a variable, but we want to increment the value stored in a variable.
In this way we must dereference b and instead refer to a by b following the pointer.
Then we add 1 to the value and store it back at the memory address stored in b.
The last line prints the value of a. You can see that the value of a has increased to 201
Function parameters in the Go language are all value copies. When we want to modify a variable, we cancreate an address pointing to the variable Pointer variable .
Different from pointers in C/C, pointers in Go language cannot be offset and operated, and are safe pointers.
To understand pointers in Go language, you need to know three concepts: Pointer address, pointer type and pointer value.
Pointer address and pointer type
Pointer operations in Go language are very simple. You only need to remember two symbols: & (take address ) and * (value based on address).
Each variable has an address at runtime, which represents the location of the variable in memory. In the Go language, the & character is used in front of the variable to "get the address" of the variable.
The syntax for taking the variable pointer is as follows:
ptr := &v // v的类型为T
Among them:
v: represents the variable of the taken address, type is T
ptr: A variable used to receive the address. The type of ptr is *T, which is called the pointer type of T. * stands for pointer.
func main() {
a := 10
b := &a
fmt.Printf("a:%d ptr:%p\n", a, &a) // a:10 ptr:0xc00001a078
fmt.Printf("b:%p type:%T\n", b, b) // b:0xc00001a078 type:*int
fmt.Println(&b) // 0xc00000e018
}Pointer operator
1. When the pointer operator is an lvalue, We can update the state of the target object; when it is an rvalue, it is to obtain the state of the target.
func main() {
x := 10
var p *int = &x //获取地址,保存到指针变量
*p += 20 //用指针间接引用,并更新对象
println(p, *p) //输出指针所存储的地址,以及目标对象
}
Output:
0xc000040780 30
2. Pointer types support equality operators, but cannot do addition, subtraction and type conversion. Two pointers are equal if they point to the same address or are both nil.
func main() {
x := 10
p := &x
p++ //编译报错 invalid operation: p++ (non-numeric type *int)
var p2 *int = p+1 //invalid operation: p + 1 (mismatched types *int and int)
p2 = &x
println(p == p2) //指向同一地址
}
You can use unsafe.Pointer to convert the pointer to uintptr and then perform addition and subtraction operations, but it may cause illegal access.
Pointer arithmetic
In many golang programs, although pointers are used, the pointers are not added or subtracted. This is different from C programs. Very different. Golang’s official introductory learning tool (go tour) even says that Go does not support pointer arithmetic. Although this is not actually the case, it seems that I have never seen pointer arithmetic in ordinary go programs (well, I know you want to write unusual programs).
- 但实际上,go 可以通过
unsafe.Pointer来把指针转换为uintptr类型的数字,来间接实现指针运算。- 这里请注意,
uintptr是一种整数类型,而不是指针类型。
比如:
uintptr(unsafe.Pointer(&p)) + 1
就得到了 &p 的下一个字节的位置。然而,根据 《Go Programming Language》 的提示,我们最好直接把这个计算得到的内存地址转换为指针类型:
unsafe.Pointer(uintptr(unsafe.Pointer(&p) + 1))
因为 go 中是有垃圾回收机制的,如果某种 GC 挪动了目标值的内存地址,以整型来存储的指针数值,就成了无效的值。
同时也要注意,go 中对指针的 + 1,真的就只是指向了下一个字节,而 C 中 + 1 或者 ++ 考虑了数据类型的长度,会自动指向当前值结尾后的下一个字节(或者说,有可能就是下一个值的开始)。如果 go 中要想实现同样的效果,可以使用 unsafe.Sizeof 方法:
unsafe.Pointer(uintptr(unsafe.Pointer(&p) + unsafe.Sizeof(p)))
最后,另外一种常用的指针操作是转换指针类型。这也可以利用 unsafe 包来实现:
var a int64 = 1 (*int8)(unsafe.Pointer(&a))
如果你没有遇到过需要转换指针类型的需求,可以看看这个项目(端口扫描工具),其中构建 IP 协议首部的代码,就用到了指针类型转换。
The above is the detailed content of What are the operations on pointers in go language?. For more information, please follow other related articles on the PHP Chinese website!
The Performance Race: Golang vs. CApr 16, 2025 am 12:07 AMGolang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.
Golang vs. C : Code Examples and Performance AnalysisApr 15, 2025 am 12:03 AMGolang is suitable for rapid development and concurrent programming, while C is more suitable for projects that require extreme performance and underlying control. 1) Golang's concurrency model simplifies concurrency programming through goroutine and channel. 2) C's template programming provides generic code and performance optimization. 3) Golang's garbage collection is convenient but may affect performance. C's memory management is complex but the control is fine.
Golang's Impact: Speed, Efficiency, and SimplicityApr 14, 2025 am 12:11 AMGoimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:
C and Golang: When Performance is CrucialApr 13, 2025 am 12:11 AMC is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.
Golang in Action: Real-World Examples and ApplicationsApr 12, 2025 am 12:11 AMGolang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.
Golang: The Go Programming Language ExplainedApr 10, 2025 am 11:18 AMThe core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.
Golang's Purpose: Building Efficient and Scalable SystemsApr 09, 2025 pm 05:17 PMGo language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.
Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Apr 02, 2025 pm 05:24 PMConfused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft







