GO Tutorial



PACKAGES AND IMPORT


📦 Understanding Packages and Importing in Go

Go organizes code using packages. Every Go file starts with a package declaration. To reuse code from another package, you use the import keyword.

📌 Tip: A package is like a folder or module that groups related Go files and functions together.

📁 1. Declaring a Package

package main
  

main is the default package used for executables. The Go program starts execution from the main() function inside the main package.

📥 2. Importing Packages

import "fmt"
  

This imports the fmt package, which is used for formatted I/O (like printing to console).

📦 3. Import Multiple Packages

Use a grouped import block:

import (
    "fmt"
    "math"
    "time"
)
  

This helps organize your imports cleanly, especially when using several standard or custom packages.

🔧 4. Example Program Using Imports

package main

import (
    "fmt"
    "math"
)

func main() {
    fmt.Println("Square root of 16 is:", math.Sqrt(16))
}
  

Output:

Square root of 16 is: 4
  

🧩 5. Custom Packages

You can create your own packages to organize code better. Example:

📁 Folder structure:

/myproject/
  ├── main.go
  └── utils/
        └── tools.go
  

tools.go

package utils

import "fmt"

func SayHello() {
    fmt.Println("Hello from utils package!")
}
  

main.go

package main

import (
    "myproject/utils"
)

func main() {
    utils.SayHello()
}
  

Use the folder name as the package name to import your own packages correctly.

🎯 Summary:
  • Every Go file starts with a package declaration
  • Use import to include standard or custom packages
  • Organize code by creating reusable packages

💡 Try It Yourself!

On Go Playground, try importing:

  • "fmt" to print
  • "math/rand" to generate a random number
  • "time" to print current time

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review