英文:
variable getter functions in golang
问题
考虑以下在Go语言中的堆栈实现:
package main
import "fmt"
var a [10]int
var top int = -1
func main() {
printStack()
push(1)
printStack()
push(23)
printStack()
pop()
push(2)
printStack()
println("Top element is", getTop)
}
func push(x int) {
top += 1
a[top] = x
}
func pop() {
top -= 1
}
func getTop() int {
return a[top]
}
func printStack() {
fmt.Println(top+1, "Stack:", a, "Top", getTop)
}
问题:
- 当我使用
println("Top element is", getTop)
时,它打印出内存地址0x193928
,但当我调用println("Top element is", getTop())
时,它返回2
。返回2
是有意义的,但我不明白为什么它返回内存地址?不带括号调用getTop
不应该是无效的吗? - 在Go语言中,似乎不能同时使用相同的变量名和函数名。这个假设是正确的吗?
Play链接:https://play.golang.org/p/vvOGG296gr
英文:
Consider the following stack implementation in go:
package main
import "fmt"
var a [10]int
var top int = -1
func main() {
printStack()
push(1)
printStack()
push(23)
printStack()
pop()
push(2)
printStack()
println("Top element is", getTop)
}
func push(x int) {
top += 1
a[top] = x
}
func pop() {
top -= 1
}
func getTop() int {
return a[top]
}
func printStack() {
fmt.Println(top+1, "Stack: ", a, "Top", getTop)
}
Questions:
- When I use
println("Top element is", getTop)
, it prints out memory address0x193928
but when I callprintln("Top element is", getTop())
, it returns2
. Returning 2 makes sense but I don't understand why its returning memory address? shouldn't call getTop without brackets be invalid? - It seems that you can't have variable & functions with same name in golang. is that correct assumption to make?
答案1
得分: 2
-
你可以将函数作为变量传递,例如:https://play.golang.org/p/wzGVtsEFQk。所以
getTop
是一个"函数指针",这解释了打印的地址。 -
根据第一点的解释:如果在同一作用域中声明,你的变量名和函数名会发生冲突。
英文:
-
You can pass your function as a var, for example: https://play.golang.org/p/wzGVtsEFQk . So
getTop
is a "function pointer", which explains the address being printed -
Explained by #1: if it is declared in the same scope, your var name and function name collide
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论