ddavison
ddavison

Reputation: 29032

How do I access functions in the main package?

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?

Upvotes: 11

Views: 15755

Answers (1)

Chris Pfohl
Chris Pfohl

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.

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!")
}

Upvotes: 17

Related Questions