Importing Local Packages in Go

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!

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Complete Guide to Python Envs (Unix/MacOS)

Generics or Metaprogramming? Declarative macros with Rust

Fl Keygen.reg

Manage Kubernetes Resources via Terraform

Run-down of AVL-trees

Monitor with code

Mechanical Analysis

Community Event: Dive Into Discord

Getting Started with Flutter on Windows

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sean Dever

Sean Dever

More from Medium

Configuration Maps in Cluster Management

A school management app built using Golang and OOP

Application Infrastructure Middleware — Growth, Trends and Competitive Market 2022–2026

MySQL-DMS prerequisite