I am new to golang and have been loving it so far. So far I've been writing all my applications logic inside the main.go
and it is starting to get quite cumbersome with so much text on the screen. I cannot for the life of me figure out how to import external functions that are located in another .go file. Here is a basic example of what I'm trying to accomplish
main.go
package main
func main() {
SayHello() //THIS IS THE FUNCTION IMPORTED FROM hello.go
{
hello.go
package hello
import "fmt"
func SayHello() {
fmt.Println("Hello!")
{
project structure
/
-main.go
-hello.go
I know this is a fairly simple question but everything I try will result in an error in my console. All I want in this example is to export the SayHello
function from the hello.go file into the main.go file, and as far as I understand anything exported must start with a capital letter. The whole go.mod file and package declaration at the top if each file confuses me and I have not been able to figure this out for hours.
CodePudding user response:
You can only have a single package per directory. If you want the code in hello.go
to live in a separate package, you need to move it into a subdirectory.
First, this assumes that you've initialized your project using go mod init <something>
. For the purposes of this example, we'll start with:
go mod init example
This creates our go.mod
file. Next, we set up the correct directory structure:
.
├── go.mod
├── hello
│ └── hello.go
└── main.go
hello.go
is correct as written (well, once you fix the syntax errors in your posted code). We'll need to add an import
to main.go
:
package main
import "example/hello"
func main() {
hello.SayHello() //THIS IS THE FUNCTION IMPORTED FROM hello.go
}
This will build an executable that produces the expected output:
$ go build
$ ./example
Hello!