gpt4 book ai didi

pointers - Go中的指针算法

转载 作者:IT老高 更新时间:2023-10-28 13:02:39 26 4
gpt4 key购买 nike

考虑到您可以(想不出一个很好的表达方式,但是)在 Go 中操作指针,是否可以像在 C 中那样执行指针运算,比如遍历数组?我知道这些天循环很适合这种事情,但我只是好奇它是否可能。

最佳答案

没有。来自 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.

话虽如此,您可以使用 unsafe 来解决这个问题。包,但只是不要:

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

关于pointers - Go中的指针算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32700999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com