dougao2830 2015-09-21 17:13
浏览 48
已采纳

Go中的指针算法

Considering you can (can't think of a great way to put it, but) manipulate pointers in Go, is it possible to perform pointer arithmetic like you would in C, say for iterating over an array? I know loops are just fine for that kind of things these days but I'm just curious if it's possible.

  • 写回答

1条回答 默认 最新

  • douyan6958 2015-09-21 17:15
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本