Navigation
We want to design our project with the following structure:
├── main.go └── models └── user.go
In this layout, main.go imports the user.go file, which defines the User type. However, the compiler warns that User is undefined in the main package.
Question
Why does this error occur, and how can we resolve it while maintaining a modular project structure?
Answer
The issue stems from the absence of a module definition in the project. Prior to Go 1.11.1, Go relied on the $GOPATH environment variable, which introduced complexities in managing project dependencies.
Go modules, introduced in Go 1.11.1 and enabled by default in Go 1.11.3, address this problem. By enabling modules (via the GO111MODULE=on environment variable), we can create modular projects with versioned dependencies and hierarchical organization.
Solution
To leverage Go modules, follow these steps:
Create a go.mod file:
/Users/myuser/Projects/my-project/ ├── go.mod ├── main.go └── src/ └── models/ └── user.go
Import user.go in main.go:
Sample main.go:
package main import ( "fmt" "main/src/models/user" ) func main() { fmt.Println(user.User{"new_user"}) }
Sample user.go:
package user type User struct { Login string }
This structure allows us to import the User type from the models/user.go file into the main.go file. The go.mod file defines the module name and serves as the project's root.
Atas ialah kandungan terperinci Mengapakah mengimport fail daripada subfolder mengakibatkan ralat 'tidak ditentukan' dalam Go dan bagaimanakah Modul Go boleh digunakan untuk menyelesaikannya sambil mengekalkan struktur projek modular?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!