Import Packages

Using external and internal packages in Go programs

📥 What is Importing Packages?

Importing packages in Go allows you to use code from other packages in your program. You can import standard library packages, third-party packages, or your own custom packages.


package main

import (
    "fmt"           // Standard library
    "math/rand"     // Standard library
    "time"          // Standard library
)

func main() {
    fmt.Println("Random number:", rand.Intn(100))
}
                                    

Output:

Random number: 42

Import Concepts

📋

Single Import

Import one package at a time

import "fmt"
📚

Multiple Imports

Import multiple packages together

import (
    "fmt"
    "time"
)
🏷️

Package Aliases

Give packages custom names

import f "fmt"

f.Println("Hello")

Blank Import

Import for side effects only

import _ "database/sql"

🔹 Basic Import Syntax

Different ways to import packages in Go:

🔸 Single Package Import:

package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}

🔸 Multiple Package Import:

package main

import (
    "fmt"
    "math"
    "strings"
)

func main() {
    fmt.Println("Square root of 16:", math.Sqrt(16))
    fmt.Println("Uppercase:", strings.ToUpper("hello"))
}

Output:

Square root of 16: 4

Uppercase: HELLO

🔹 Package Aliases

Use aliases to avoid naming conflicts or shorten long package names:

package main

import (
    "fmt"
    f "fmt"                    // Alias 'f' for fmt
    str "strings"              // Alias 'str' for strings
    "math/rand"
    r "math/rand"              // Alias 'r' for rand
)

func main() {
    // Using original names
    fmt.Println("Original fmt")
    
    // Using aliases
    f.Println("Aliased fmt")
    
    result := str.ToUpper("hello")
    fmt.Println("Strings result:", result)
    
    number := r.Intn(100)
    fmt.Println("Random number:", number)
}

Output:

Original fmt

Aliased fmt

Strings result: HELLO

Random number: 73

🔹 Dot Import

Import package contents directly into current namespace:

package main

import (
    . "fmt"        // Dot import - use functions directly
    . "math"       // Import math functions directly
)

func main() {
    // No need to prefix with package name
    Println("Hello from dot import!")
    Println("Square root of 25:", Sqrt(25))
    Println("Value of Pi:", Pi)
}

Output:

Hello from dot import!

Square root of 25: 5

Value of Pi: 3.141592653589793

⚠️ Warning:

Dot imports can make code harder to read and cause naming conflicts. Use sparingly!

🔹 Blank Import

Import packages for their side effects without using them directly:

package main

import (
    "fmt"
    _ "math/rand"    // Blank import for initialization
    "time"
)

func init() {
    // This runs when the package is imported
    fmt.Println("Package initialized")
}

func main() {
    fmt.Println("Main function")
    fmt.Println("Current time:", time.Now().Format("15:04:05"))
}

Output:

Package initialized

Main function

Current time: 14:30:25

🔹 Importing Custom Packages

Import your own packages from the same project:

🔸 Project Structure:

// myproject/
//   ├── main.go
//   ├── utils/
//   │   └── helper.go
//   └── models/
//       └── user.go

// File: utils/helper.go
package utils

import "strings"

func Capitalize(s string) string {
    if len(s) == 0 {
        return s
    }
    return strings.ToUpper(s[:1]) + s[1:]
}

// File: models/user.go
package models

type User struct {
    ID   int
    Name string
}

func NewUser(id int, name string) User {
    return User{ID: id, Name: name}
}

🔸 File: main.go

package main

import (
    "fmt"
    "myproject/utils"    // Import custom package
    "myproject/models"   // Import another custom package
)

func main() {
    // Use custom packages
    name := utils.Capitalize("john doe")
    user := models.NewUser(1, name)
    
    fmt.Printf("User: %+v\n", user)
}

Output:

User: {ID:1 Name:John doe}

🧠 Test Your Knowledge

What does the blank import (_ "package") do?