Reputation: 29032
Per the setup:
$GOPATH/
github.com/ddavison/project/
subpackage/
lib.go
main.go
package subpackage
...
func Hello() {
fmt.Println("hello")
}
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
?
Upvotes: 11
Views: 15755
Reputation: 19044
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
.
package subpackage
...
type Complete func()
func Hello(complete Complete) {
fmt.Println("hello")
complete()
}
package main
...
func main() {
subpackage.Hello(DoSomethign)
}
func DoSomething() {
fmt.Println("done!")
}
Upvotes: 17