How to Import Package in Go: Syntax and Examples
In Go, you import a package using the
import keyword followed by the package path in quotes. You can import single or multiple packages by listing them inside parentheses after import.Syntax
The basic syntax to import a package in Go is using the import keyword followed by the package path in quotes. For multiple packages, use parentheses to group them.
- import "package/path": imports a single package.
- import ("pkg1" "pkg2"): imports multiple packages.
go
import "fmt" // or import ( "fmt" "math" )
Example
This example shows how to import the fmt package to print text and the math package to calculate the square root.
go
package main import ( "fmt" "math" ) func main() { fmt.Println("Hello, Go!") fmt.Println("Square root of 16 is", math.Sqrt(16)) }
Output
Hello, Go!
Square root of 16 is 4
Common Pitfalls
Common mistakes when importing packages include:
- Forgetting to import the package before using it causes a compile error.
- Importing a package but not using it results in a compile error.
- Using incorrect package paths or misspelling them.
- Not grouping multiple imports properly with parentheses.
Here is an example of a wrong and right way:
go
// Wrong: Using fmt without import package main func main() { fmt.Println("Hello") // Error: undefined fmt } // Right: package main import "fmt" func main() { fmt.Println("Hello") }
Quick Reference
Tips for importing packages in Go:
- Use
importkeyword followed by package path in quotes. - Group multiple imports inside parentheses.
- Unused imports cause compile errors; remove or use them.
- Use aliasing to rename imports if needed:
import alias "package/path".
Key Takeaways
Use the import keyword followed by the package path in quotes to import packages in Go.
Group multiple imports inside parentheses for cleaner code.
Always use imported packages to avoid compile errors.
Check package paths carefully to avoid misspelling errors.
Use import aliasing to rename packages when needed.