variable getter functions in golang

huangapple go评论115阅读模式
英文:

variable getter functions in golang

问题

考虑以下在Go语言中的堆栈实现:

  1. package main
  2. import "fmt"
  3. var a [10]int
  4. var top int = -1
  5. func main() {
  6. printStack()
  7. push(1)
  8. printStack()
  9. push(23)
  10. printStack()
  11. pop()
  12. push(2)
  13. printStack()
  14. println("Top element is", getTop)
  15. }
  16. func push(x int) {
  17. top += 1
  18. a[top] = x
  19. }
  20. func pop() {
  21. top -= 1
  22. }
  23. func getTop() int {
  24. return a[top]
  25. }
  26. func printStack() {
  27. fmt.Println(top+1, "Stack:", a, "Top", getTop)
  28. }

问题:

  1. 当我使用println("Top element is", getTop)时,它打印出内存地址0x193928,但当我调用println("Top element is", getTop())时,它返回2。返回2是有意义的,但我不明白为什么它返回内存地址?不带括号调用getTop不应该是无效的吗?
  2. 在Go语言中,似乎不能同时使用相同的变量名和函数名。这个假设是正确的吗?

Play链接:https://play.golang.org/p/vvOGG296gr

英文:

Consider the following stack implementation in go:

  1. package main
  2. import "fmt"
  3. var a [10]int
  4. var top int = -1
  5. func main() {
  6. printStack()
  7. push(1)
  8. printStack()
  9. push(23)
  10. printStack()
  11. pop()
  12. push(2)
  13. printStack()
  14. println("Top element is", getTop)
  15. }
  16. func push(x int) {
  17. top += 1
  18. a[top] = x
  19. }
  20. func pop() {
  21. top -= 1
  22. }
  23. func getTop() int {
  24. return a[top]
  25. }
  26. func printStack() {
  27. fmt.Println(top+1, "Stack: ", a, "Top", getTop)
  28. }

Questions:

  1. When I use println("Top element is", getTop), it prints out memory address 0x193928 but when I call println("Top element is", getTop()), it returns 2. Returning 2 makes sense but I don't understand why its returning memory address? shouldn't call getTop without brackets be invalid?
  2. It seems that you can't have variable & functions with same name in golang. is that correct assumption to make?

Play: https://play.golang.org/p/vvOGG296gr

答案1

得分: 2

  1. 你可以将函数作为变量传递,例如:https://play.golang.org/p/wzGVtsEFQk。所以getTop是一个"函数指针",这解释了打印的地址。

  2. 根据第一点的解释:如果在同一作用域中声明,你的变量名和函数名会发生冲突。

英文:
  1. 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

  2. Explained by #1: if it is declared in the same scope, your var name and function name collide

huangapple
  • 本文由 发表于 2015年11月8日 17:24:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/33592478.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定