Incrementing a pointer in Go

huangapple go评论80阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2016年12月9日 02:27:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/41046389.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定