尝试理解闭包

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

Trying to understand closures

问题

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

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

package main

import "log"

func myfunc(a int) bool {
  func otherfunc(b int) bool {
    return false
  }
  log.Println(otherfunc(2))
  return true
}

func main() {
  myfunc(1)
  log.Println("here")
}

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

英文:

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

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

package main

import "log"


func myfunc(a int) bool{
  func otherfunc(b int) bool{
    return false
  }
  log.Println(otherfunc(2))
  return true
}

func main() {
        myfunc(1)
	log.Println("here")
}

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

答案1

得分: 1

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

func myfunc(a int) bool {
  otherfunc := func(b int) bool {
    return false
  }
  log.Println(otherfunc(2))
  return true
}

顺便说一下,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

func myfunc(a int) bool {
  otherfunc := func(b int) bool {
    return false
  }
  log.Println(otherfunc(2))
  return true
}

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:

确定