Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access functions in the main package?

Tags:

go

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?

like image 870
ddavison Avatar asked Mar 16 '15 13:03

ddavison


People also ask

How do I use a function from another package?

The function to be used in another package must start with a capital letter i.e func Fullname(element,element2 string) string{} , so that it will be public outside its package. Once defined using the lower case syntax i.e func fullName()string{} its only accessible with thin that package.

What is main package?

A main package is primarily a container for repository objects that belong together, in that they share the same system, transport layer, and customer delivery status. However, a main package cannot contain any further repository objects except of its package interfaces and subpackages.

Can you import from Main in go?

The reason is simple, the packages in Go program must have unique import paths, but as the main package must have the import path “main”, you can't import another “main” package. go build works with the module named main because nothing ends up importing the resulting package.


1 Answers

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!")
}
like image 131
Chris Pfohl Avatar answered Oct 06 '22 01:10

Chris Pfohl