0
0
GoHow-ToBeginner · 3 min read

How to Use Alias Import in Go: Simple Guide with Examples

In Go, you can use alias import by specifying a new name before the package path in the import statement, like import newName "package/path". This lets you refer to the package with the alias newName in your code, making it clearer or avoiding name conflicts.
📐

Syntax

The alias import syntax in Go lets you rename a package when importing it. You write the alias name first, then the package path in quotes.

  • aliasName: The new name you want to use for the package.
  • "package/path": The original package path you want to import.
go
import aliasName "package/path"
💻

Example

This example shows how to import the fmt package with an alias f and use it to print text.

go
package main

import f "fmt"

func main() {
    f.Println("Hello using alias import!")
}
Output
Hello using alias import!
⚠️

Common Pitfalls

Common mistakes include:

  • Forgetting to use the alias name in code after aliasing the import.
  • Using the original package name instead of the alias, causing errors.
  • Choosing alias names that conflict with other variables or packages.

Always use the alias name exactly as declared.

go
package main

import f "fmt"

func main() {
    // Wrong: using original package name
    // fmt.Println("This will cause an error")

    // Right: use alias
    f.Println("This works with alias")
}
Output
This works with alias
📊

Quick Reference

ConceptDescriptionExample
Alias ImportRename a package on importimport f "fmt"
Use AliasCall package functions with aliasf.Println("text")
Avoid ConflictsUse alias to prevent name clashesimport jsoniter "github.com/json-iterator/go"

Key Takeaways

Use alias import by writing the alias before the package path in import statements.
Always refer to the package using the alias name in your code after aliasing.
Alias imports help avoid name conflicts and make code clearer.
Choose meaningful alias names to improve code readability.
Incorrect use of original package name after aliasing causes errors.