How to Create Package in Go: Simple Guide for Beginners
In Go, you create a package by placing your Go files in a folder with a
package declaration at the top. Use package packagename to name it, then import it in other files with import "packagename" to use its functions or types.Syntax
To create a package in Go, start your Go file with the package keyword followed by the package name. This name is how other files will refer to it. For example:
- package packagename: Declares the package name.
- Functions or variables declared after belong to this package.
- Files in the same folder should share the same package name.
go
package packagename
func Hello() string {
return "Hello from package"
}Example
This example shows how to create a package named greetings with a function, then use it in the main package.
go
// greetings/greetings.go package greetings func Hello() string { return "Hello, Go packages!" } // main.go package main import ( "fmt" "greetings" ) func main() { message := greetings.Hello() fmt.Println(message) }
Output
Hello, Go packages!
Common Pitfalls
Some common mistakes when creating packages in Go include:
- Using different package names in files within the same folder.
- Not exporting functions or variables (names must start with a capital letter to be accessible outside the package).
- Incorrect import paths, especially when using modules.
Example of wrong and right usage:
go
// Wrong: function not exported (starts with lowercase) package greetings func hello() string { return "hello" } // Right: function exported (starts with uppercase) package greetings func Hello() string { return "hello" }
Quick Reference
| Concept | Description |
|---|---|
| package packagename | Declares the package name at the top of Go files |
| Exported names | Start with uppercase to be accessible outside the package |
| Import path | Use import statement with package path to use it |
| Folder structure | Files in the same folder share the same package name |
| main package | Special package where program execution starts |
Key Takeaways
Start Go files with 'package packagename' to create a package.
Export functions by capitalizing their names to use them outside the package.
Keep all files in the same folder under the same package name.
Import packages using their folder or module path to access their code.
The 'main' package is special and runs your program's entry point.