来自Python,我目前正在学习Go,并试图将自己的头缠在指针上。
我写了这段代码是为了理解这个概念:
a := 1
b := &a
fmt.Println(b) // Shows the memory address of a
fmt.Println(*b) // Shows the value 1
*b++
fmt.Println(a) // Shows the value 2 (as expected)
我尝试使用此代码来增进理解。但是,以下内容不起作用:
a := 1
b := &a
fmt.Println(b) // Shows the memory address of a
fmt.Println(*b) // Shows the value 1
b = *b + 1 // Compile error: invalid operation: b * +1 (mismatched types *int and int)
fmt.Println(a)
显然,*b
是type *int
,而值1
(显然)是type int
。但是,为什么*b++
在第一个示例中可以增加a的值?
从一开始就:
b := &a
此处b
的类型是*int
,指向内存中存储值的位置的指针a
。这样做时*b
,您正在访问位置b
指针所指向的值。
当您这样做时*b++
,它代表*b = *b + 1
您要增加的位置b
指针所指向的值。
b = *b + 1
之所以无效,是因为您试图将*b
和1
都为的类型添加int
到b
,这是一个指针(为的类型*int
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句