英文:
Incrementing a pointer in Go
问题
有人可以告诉我如何在Go语言中通过字符串递增指针吗?
我尝试了类似于C语言中的ptr += 1
,但是它显示指针类型*string和int不兼容。谢谢。
英文:
Could anyone tell me how to increment a pointer through a string in Go?
I've tried ptr += 1
like in C but it says that the types *string and int are incompatible. Thanks
答案1
得分: 5
指针算术是一种在某些编程语言中允许直接对指针进行加减操作的特性。然而,在Go语言中是不支持指针算术的。这是出于安全性的考虑。没有指针算术,可以确保语言不会产生错误的地址。现代的编译器和硬件技术已经发展到了一个地步,使用数组索引的循环可以和使用指针算术的循环一样高效。此外,没有指针算术可以简化垃圾回收器的实现。所以,在Go语言中是不能对指针进行递增操作的。
更多信息可以参考这里。
英文:
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.
So the answer is no, you can't increment a pointer in Go.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论