如何访问主包中的函数?

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

How do I access functions in the main package?

问题

根据设置:

$GOPATH/
  github.com/ddavison/project/
    subpackage/
      lib.go
    main.go

###lib.go

package subpackage
...
func Hello() {
  fmt.Println("hello")
}

###main.go

package main
...
func main() {
  ...
}

func DoSomething() {
  fmt.Println("done!")
}

main.go 中,我知道我可以通过以下方式调用 lib.go 的函数:

import "github.com/ddavison/project/subpackage"
lib.Hello()

但是如何反过来,从 lib.go 中调用 main.go 的方法呢?如何从 lib.go 中调用 DoSomething()

英文:

Per the setup:

$GOPATH/
  github.com/ddavison/project/
    subpackage/
      lib.go
    main.go

###lib.go

package subpackage
...
func Hello() {
  fmt.Println("hello")
}

###main.go

package main
...
func main() {
  ...
}

func DoSomething() {
  fmt.Println("done!")
}

From main.go, I know that I am able to call lib.go's functions by doing

import "github.com/ddavison/project/subpackage"
lib.Hello()

But how can I do the inverse, call a method from main.go from lib.go? How can I call DoSomething() from lib.go?

答案1

得分: 16

Go的函数是一等公民。将命名函数DoSomething作为参数传递给lib函数。

如果允许其他内容引用main,就会产生循环依赖。

lib.go

package subpackage
...

type Complete func()

func Hello(complete Complete) {
  fmt.Println("hello")
  complete()
}

main.go

package main
...
func main() {
  subpackage.Hello(DoSomething)
}

func DoSomething() {
  fmt.Println("done!")
}
英文:

Go's funtions are first-class. Pass the named function DoSomething as a parameter to the lib function.

You'd have a circular dependency if anything else was allowed to reference main.

lib.go

package subpackage
...

type Complete func()

func Hello(complete Complete) {
  fmt.Println("hello")
  complete()
}

main.go

package main
...
func main() {
  subpackage.Hello(DoSomethign)
}

func DoSomething() {
  fmt.Println("done!")
}

huangapple
  • 本文由 发表于 2015年3月16日 21:10:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/29077678.html
匿名

发表评论

匿名网友

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

确定