I have two packages main
and test
. I’m working on test
package and I need to import a struct that is decalared inside main
package, but it seems to be impossible!
This is my directory structure:
root/
├── test/
│ └── test.go
├── main.go
└── go.mod
go.mod
:
module my_project
go 1.20
main.go
:
package main
import "my_project/test"
type MainStruct struct {
Name string
}
func main() {
test.TestFunction()
}
test.go
:
package test
func TestFunction() {
// I want to access 'MainStruct' here
}
Is it possible to import from parent package?
To access a struct defined in the main
package from another package in Go, it’s recommended to refactor your code. The main
package is typically not designed to be imported by other packages. Instead, you can create a separate package for shared types and functions. Here’s how you can restructure your project:
Create a Shared Package: Move the MainStruct
to a new package, say shared
. This package can be imported by both your main
and test
packages.
Directory Structure:
Reorganize your project like this:
root/
├── shared/ # Shared package
│ └── shared.go
├── test/ # Test package
│ └── test.go
├── main.go
└── go.mod
shared.go:
package shared
type MainStruct struct {
Name string
}
main.go:
package main
import (
"my_project/shared"
"my_project/test"
)
func main() {
s := shared.MainStruct{Name: "Example"}
test.TestFunction(s)
}
test.go:
package test
import (
"fmt"
"my_project/shared"
)
func TestFunction(s shared.MainStruct) {
fmt.Println(s.Name)
}
go.mod:
Ensure your go.mod
file has the correct module path.
This approach makes your code modular, reusable, and aligns with Go’s package design principles. It also helps in avoiding circular dependencies.
There is no parent/child package hierarchy, and you cannot import
main
(even if this were possible, you would have an import cycle which is also not allowed)Declare the type in a third package. Import that package in
my_project
andmy_project/test
.