指针算术在走 [英] pointer arithmetic in go
问题描述
从 Go FAQ :
为什么没有指针算术?
安全。如果没有指针算术,可以创建一种永远不会导致错误地成功的非法地址的语言。编译器和硬件技术已经发展到使用数组索引的循环可以像使用指针运算的循环一样高效。另外,缺少指针算术可以简化垃圾收集器的实现。
这就是说,你可以通过使用 不安全
包,但不包含:
包主
$ b $导入fmt
导入不安全
func main(){
vals:= [] int {10,20,30,40}
start:= unsafe.Pointer(& vals [0])
size:= unsafe.Sizeof(int(0))
for i:= 0;我< LEN(瓦尔斯); i ++ {
item:= *(* int)(unsafe.Pointer(uintptr(start)+ size * uintptr(i)))
fmt.Println(item)
}
}
https://play.golang.org/p/QCHEQqy6Lg
Considering you can (can't think of a great way to put it, but) manipulate pointers in golang, is it possible to perform pointer arithmetic in golang like you would in C, say for iterating over an array? I know loops are just fine for that kind of things these days, I'm just curious if it's possible.
No. From the Go FAQ:
Why is there no pointer arithmetic?
Safety. Without pointer arithmetic it's possible to create a language that can never derive an illegal address that succeeds incorrectly. Compiler and hardware technology have advanced to the point where a loop using array indices can be as efficient as a loop using pointer arithmetic. Also, the lack of pointer arithmetic can simplify the implementation of the garbage collector.
That being said, you can get around this by using the unsafe
package, but just don't:
package main
import "fmt"
import "unsafe"
func main() {
vals := []int{10, 20, 30, 40}
start := unsafe.Pointer(&vals[0])
size := unsafe.Sizeof(int(0))
for i := 0; i < len(vals); i++ {
item := *(*int)(unsafe.Pointer(uintptr(start) + size*uintptr(i)))
fmt.Println(item)
}
}
https://play.golang.org/p/QCHEQqy6Lg
这篇关于指针算术在走的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!