Yes, a Go program can have multiple packages. In Go, packages are used to organize and encapsulate code. Each package can contain its own functions, types, and variables, and you can import these packages into other Go files to use their functionality.
To create a Go program with multiple packages, you typically:
- Create a directory for each package.
- Define a Go file in each directory with the
packagekeyword at the top. - Use the
importstatement in your main package to include the other packages.
Here's a simple example:
Directory Structure:
/myproject
/mypackage
mypackage.go
main.go
mypackage/mypackage.go:
package mypackage
import "fmt"
func Hello() {
fmt.Println("Hello from mypackage!")
}
main.go:
package main
import (
"myproject/mypackage"
)
func main() {
mypackage.Hello()
}
In this example, the main package imports mypackage and calls the Hello function defined in it.
