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
?
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.
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.
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.
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!")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With