英文:
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!")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论