【发布时间】:2019-02-13 10:02:06
【问题描述】:
我来自 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 是 *int 类型,而值 1 是(显然)int 类型。但是,为什么可以在第一个示例中使用 *b++ 增加 a 的值?
【问题讨论】:
-
*b++代表*b = *b + 1,而不是b = *b + 1。 -
b的类型为*int。*b的类型为int。*b + 1很好(并产生int)。问题是分配给b,它是*int,而不是int。写b = *b或b = 1会得到同样的错误。 -
您使用的是什么 Go 版本?我没有收到您发布的错误;我得到“不能使用 *b + 1 (type int) as type *int in assignment”;这更清楚,在这种情况下可能会避免你的困惑。