Junior
How to create and import packages in Go?
sobes.tech AI
Answer from AI
Creating a package:
- Create a directory with a name that matches the package name.
- Create a
.gofile in this directory. - At the beginning of the file, specify the package declaration with the keyword
package, followed by the package name:package mypackage // Package name - Exported identifiers (variables, functions, types) that are accessible from other packages should start with an uppercase letter.
Importing a package:
In another .go file where you need to use the package:
- Use the
importstatement at the beginning of the file, after the package declaration and before function declarations:The path to the package depends on its location relative toimport "path/to/mypackage" // Path to the packageGOPATHor the Go module.
Example of creating and using a package:
Suppose we have the following project structure:
myproject/
├── main.go
└── mypackage/
└── constants.go
File mypackage/constants.go:
package mypackage
// MyConstant is exported because it starts with an uppercase letter
const MyConstant = "Hello from mypackage"
// myInternalConstant is not exported
const myInternalConstant = "This stays here"
File main.go:
package main
import (
"fmt"
"log" // Importing the standard library
"myproject/mypackage" // Importing our package
)
func main() {
fmt.Println("Using constant from mypackage:")
fmt.Println(mypackage.MyConstant) // Access to the exported constant
// fmt.Println(mypackage.myInternalConstant) // Compilation error: myInternalConstant is not exported
log.Println("Program finished.") // Using the log package
}
When using Go modules (the recommended way), the package path usually matches the path in your repository or go.mod. In the example above, myproject is the module name.
Possible import options:
- Standard import:
import "fmt" - Import with alias:
import f "fmt"(usage:f.Println(...)) - Dot import (not recommended for general use):
import . "fmt"(usage:Println(...)) - Blank identifier import (to execute the package without explicitly using its contents, e.g., for registering drivers):
import _ "database/sql/driver"