Importing Local Packages in Go

Sean Dever
2 min readDec 27, 2020
Photo by Matt Seymour on Unsplash

We all know that with go, we need a “main.go” file to execute in order to run our application. And though we can hold everything within a main.go file, as our app gets larger in size and more functions are made things could get really messy really fast. As good developers, we want to have clean, easy to read code and we want to separate our concerns and abstract the functions, and organize them into different groups.

If you’ve ever used any of the other built-in Go packages like “fmt” you’re already halfway there!

package mainimport "fmt"func main() {
fmt.Println("Hello, world")
}

When importing local packages, however, there are some rules we need to abide by:

  1. For the functions, structs, variables, or other types of data we’re exporting, the first letter must be capitalized.
  2. You must have the correct path to the file you’re importing

Here is an example of an application structure

application-name
├── Example
| |──example.go
|
└── main.go

example.go:

package exampleimport "fmt"var Message string = "An apple a day will keep the doctor away"type User struct {
name string
age int32
location string
}
func SayHello(str string) {
fmt.Println("Hello, %v!!", str)
}

main.go

package mainimport (
Example "app-name/Example"
"fmt"
)
func main() {
fmt.Println(Example.Message)
Example.SayHello("User")
fmt.Println(Example.User{name: "NewUser", age: 25, location: "The World"}

Hopes this helps to organize your projects! Happy Hacking!

--

--