有人可以在GO lang ..中解释&和*之间的区别,并提供何时使用&和*来说明区别的示例吗?从我阅读的内容来看,它们都与访问变量存储位置有关,但是我不确定何时使用&或*。
这是一个非常简单的示例,说明了&
和*
的用法。请注意,*
它可用于两种不同的情况1)将变量声明为指针2)取消引用指针。
package main
import "fmt"
func main() {
b := 6
var b_ptr *int // *int is used delcare variable
// b_ptr to be a pointer to an int
b_ptr = &b // b_ptr is assigned value that is the address
// of where variable b is stored
// Shorhand for the above two lines is:
// b_ptr := &b
fmt.Printf("address of b_ptr: %p\n", b_ptr)
// We can use *b_ptr get the value that is stored
// at address b_ptr, or dereference the pointer
fmt.Printf("value stored at b_ptr: %d\n", *b_ptr)
}
结果:
address of b_ptr: 0xc82007c1f0
value stored at b_ptr: 6
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句