尝试理解闭包

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

Trying to understand closures

问题

抱歉,我只能提供中文翻译。以下是您提供的代码的翻译:

抱歉,我在Go语言方面还是个新手。我正在尝试编写一个闭包:

  1. package main
  2. import "log"
  3. func myfunc(a int) bool {
  4. func otherfunc(b int) bool {
  5. return false
  6. }
  7. log.Println(otherfunc(2))
  8. return true
  9. }
  10. func main() {
  11. myfunc(1)
  12. log.Println("here")
  13. }

在Python中,类似的函数可以正常工作。为什么在Go中无法正常工作?

英文:

Sorry, still a newb in Go. I am trying to write a closure:

https://play.golang.org/p/qz-8WFh0mv

  1. package main
  2. import "log"
  3. func myfunc(a int) bool{
  4. func otherfunc(b int) bool{
  5. return false
  6. }
  7. log.Println(otherfunc(2))
  8. return true
  9. }
  10. func main() {
  11. myfunc(1)
  12. log.Println("here")
  13. }

A similar function in Python would work. Why doesn't this work in Go?

答案1

得分: 1

你需要将内部函数定义为局部变量。尝试这样做:

  1. func myfunc(a int) bool {
  2. otherfunc := func(b int) bool {
  3. return false
  4. }
  5. log.Println(otherfunc(2))
  6. return true
  7. }

顺便说一下,otherfunc := func(b int) bool {var otherfunc func(int) bool = func(b int) bool { 的简写形式。

可以参考以下示例:

https://gobyexample.com/closures

https://gobyexample.com/variables

英文:

You need to define the inner func as a local variable. Try this

  1. func myfunc(a int) bool {
  2. otherfunc := func(b int) bool {
  3. return false
  4. }
  5. log.Println(otherfunc(2))
  6. return true
  7. }

Btw. otherfunc := func(b int) bool { is shorthand for var otherfunc func(int) bool = func(b int) bool {

Look at these examples

https://gobyexample.com/closures

https://gobyexample.com/variables

huangapple
  • 本文由 发表于 2016年2月27日 12:37:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/35665727.html
匿名

发表评论

匿名网友

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

确定