What does that mean when we say uintptr stores the uninterpreted bits of a pointer value?

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

What does that mean when we say uintptr stores the uninterpreted bits of a pointer value?

问题

uintptr在golang的官方网站上解释为存储指针值的未解释位,但我在网上找到的答案非常令人困惑。有人可以用简单的话解释一下吗?

英文:

I read in golang website that uintptr stores the uninterpreted bits of a pointer value, the kind of anwsers that i found on web were very confusing.Can someone please explaing this to me in simple words .

答案1

得分: 7

简短回答:当你需要将地址视为数字使用时,就会使用它。

Go是一种带有垃圾回收机制的语言。Go始终准确地知道何时一个东西是指针,何时它只是一个值。Go需要这种知识来查找可以释放的旧未使用的值。在Go中,指针也是特殊的,你不能像在C中那样将一个数字加到指针上。

但是有时,当你在嵌入式系统或某种低级库中工作时,需要对地址进行加减操作,你需要告诉Go不要检查这个指针,因为它当前并没有指向有用的东西。你只是想将这个地址视为数字,并将另一个数字加减到它上面。

这就是你会使用uintptr的地方。这种类型可以保存任何指针值(任何地址),当你将一个地址放入其中时,Go不会将其视为指针,因此你可以随意操作它。

英文:

Short answer: it's used when you need to use an address as if it's a number.

Go is a garbage-collected language. Go always knows exactly, when a thing is a pointer, and when it's just a value. Go needs this knowledge to look for old unused values that it can free. Pointers are also special in Go in that you can't just add a number to a pointer like you would do in C.

But sometimes, when you work with embedded systems or some kind of low-level libraries where you need to add or subtract from an address, you need to tell Go that it shouldn't check this pointer because it's not pointing to anything useful at the moment. You just want to use this address as if it was a number and add/subtract another number to it.

This is where you would use uintptr. This type can hold any pointer value (any address), and when you put an address into it, Go doesn't see it as a pointer, so you can do whatever you want with it.

huangapple
  • 本文由 发表于 2015年2月11日 20:12:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/28454089.html
匿名

发表评论

匿名网友

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

确定