In Go, you can import local packages by specifying the relative path to the package directory from the current Go module. Here’s how you can import a local package:
Project Structure:
Suppose you have the following project structure:
myproject/ │ ├── main.go └── mypackage/ └── mypackage.go
1. Create a Go Module (Optional):
If you haven’t initialized your project as a Go module yet, you can do so by running the following command in the project root:
go mod init myproject
2. Write Your Package:
In the `mypackage/mypackage.go` file, define your package:
package mypackage import "fmt" func Hello() { fmt.Println("Hello from mypackage!") }
3. Import Your Package in `main.go`:
In your `main.go` file or any other Go file within your project, import your local package using its relative path:
package main import ( "myproject/mypackage" ) func main() { mypackage.Hello() }
4. Run Your Program:
Run your Go program as usual:
go run main.go
Note:
1. Go packages are organized using directories, and their names are based on the last segment of the import path.
2. If your project is not a Go module, make sure your `GOPATH` environment variable is correctly set. In a non-module project, packages should be placed under the `src` directory within the `GOPATH`.
3. If your package is part of a Go module, the import path should be relative to the module root.
4. The `go mod init` command is only necessary if you’re working with Go modules. If you’re not using modules, make sure your project is structured within your `GOPATH`.
5. You can also import local packages using their full path from your `GOPATH`, but this is not recommended unless your project is not using Go modules.