How to Use Dot Import in Go: Syntax and Examples
In Go, a
dot import allows you to import a package so that you can use its exported names without a package prefix. You do this by writing import . "package/path". This can make code shorter but may reduce clarity.Syntax
The dot import syntax in Go looks like this:
import . "package/path"Here, the dot . means you can use the package's exported functions, types, and variables directly without the package name prefix.
- import: keyword to include a package
.: dot import indicator- "package/path": the path of the package to import
go
package main import . "fmt" func main() { Println("Hello from dot import!") }
Output
Hello from dot import!
Example
This example shows how to use dot import with the standard fmt package. Notice that Println is called directly without fmt. prefix.
go
package main import . "fmt" func main() { Println("Dot import example in Go") }
Output
Dot import example in Go
Common Pitfalls
Dot imports can make code harder to read because it is unclear which package a function or type comes from. It can also cause name conflicts if multiple packages export the same names.
Use dot imports sparingly, mostly in tests or small scripts.
go
package main // Wrong: causes confusion and possible name conflicts import . "fmt" import . "math" func main() { // Which Sqrt is this? math.Sqrt or fmt.Something? Println(Sqrt(16)) } // Better: use package prefixes for clarity // import "fmt" // import "math" // func main() { // fmt.Println(math.Sqrt(16)) // }
Quick Reference
- Use
import . "package/path"to enable dot import. - Access exported names without package prefix.
- Use carefully to avoid name conflicts and reduce confusion.
- Commonly used in tests or small examples.
Key Takeaways
Dot import lets you use package members without prefix by writing import . "package/path".
It can make code shorter but may reduce readability and cause name conflicts.
Use dot imports only when it improves clarity, such as in tests or small scripts.
Avoid dot imports in large projects to keep code clear and maintainable.