指针算术在走 [英] pointer arithmetic in go

查看:140
本文介绍了指针算术在走的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到你可以(不能想到一个很好的方式来放置它,但是)在golang中操纵指针,是否有可能在golang中执行指针运算,就像你在C中执行指针运算一样,比如说迭代数组?我知道循环对于那些日子来说很好,我只是好奇如果可能的话。

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆