查找常量的地址 [英] Find address of constant in go
问题描述
包主
$ b $ func main(){
const k = 5
address:=& k
}
它给出了一个错误,谁能告诉我们如何找到一个常量的地址?
不能。错误讯息显示:
不能接收地址k
地址运算符& $的操作数有限制C $ C>。 规范:地址运营商:
对于
T
类型的操作数x
,地址操作& ; x
生成一个类型为* T
到x
的指针。操作数必须是 addressable ,即变量,指针间接或片段索引操作;或可寻址结构操作数的字段选择器;或可寻址阵列的数组索引操作。作为可寻址性要求的一个例外,x
也可能是一个(可能加了括号的)复合文字。如果对x
的评估会导致运行时恐慌,那么对& x
的评估也是如此。
常量不是列为可寻址,并且规范中没有列出可寻址(以上引用)的东西不能是地址运算符 不允许采用常量的地址。这有两个原因: 如果您需要一个指向等于该常量的值的指针,请将其指定给一个可寻址的变量,以便您可以取其地址,例如 但是知道在Go中数字常量表示任意精度的值,并且不溢出。当你把一个常量的值赋给一个变量时,它可能是不可能的(例如,常量可能大于你指定的变量类型的最大值 - 导致编译时错误),或者它可能不是一样的(例如,在浮点常量的情况下,它可能会失去精度)。 We have written one program by which we try to find an address of a constant. Is it possible to do it like that? It gives an error, can anyone tell how can we find the address of a constant? In short: you can't. The error message says: cannot take the address of k There are limitations on the operand of the address operator For an operand Constants are not listed as addressable, and things that are not listed in the spec as addressable (quoted above) cannot be the operand of the address operator It is not allowed to take the address of a constant. This is for 2 reasons: If you need a pointer to a value being equal to that constant, assign it to a variable of which is addressable so you can take its address, e.g. But know that in Go numeric constants represent values of arbitrary precision and do not overflow. When you assign the value of a constant to a variable, it may not be possible (e.g. the constant may be greater than the max value of the variable's type you're assigning it to - resulting in compile-time error), or it may not be the same (e.g. in case of floating point constants, it may lose precision). 这篇关于查找常量的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!&
的操作数(不能取它们的地址)。
func main(){
const k = 5
v:= k
地址:=& v // This是允许的
$ / code> package main
func main() {
const k = 5
address := &k
}
&
. Spec: Address operators:
x
of type T
, the address operation &x
generates a pointer of type *T
to x
. The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement, x
may also be a (possibly parenthesized) composite literal. If the evaluation of x
would cause a run-time panic, then the evaluation of &x
does too.&
(you can't take the address of them).
func main() {
const k = 5
v := k
address := &v // This is allowed
}