variable getter functions in golang

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

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)
}

问题:

  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:

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:

  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:

确定