英文:
How to Import Local Package in Golang
问题
我有一个问题。我无法在我的应用程序中导入本地包。
type Post struct {
URL string `json:"url,omitempty"`
Caption string `json:"caption,omitempty"`
Likes []User `json:"likes,omitempty"` // 无法从user包中导入User
}
type User struct {
Name string `json:"name,omitempty"`
Password string `json:"password,omitempty"`
Followers []User `json:"followers,omitempty"`
Followings []User `json:"followings,omitempty"`
}
英文:
i have a problem. I cannot import local packages in my application.
type Post struct {
URL string `json:"url,omitempty"`
Caption string `json:"caption,omitempty"`
Likes []User `json:"likes,omitempty"` // Can not import User from package user
}
type User struct {
Name string `json:"name,omitempty"`
Password string `json:"password,omitempty"`
Followers []User `json:"followers,omitempty"`
Followings []User `json:"followings,omitempty"`
}
</details>
# 答案1
**得分**: 1
我为您的情景创建了一个示例结构,如下所示:
假设项目结构如下所示:
project-villa/ //您的项目名称
model/
-user.go //此文件将包含您的用户结构
repository/
-post.go //此文件将保存您的帖子结构和其他代码片段
handler/
driver/
main.go
步骤1:初始化模块
go mod init project-villa
或者
go mod init github.com/user-name/project-villa
模块将自行管理模块依赖关系。无论如何,如果它没有,您可以显式导入它。
它将如下所示:
github.com/random/project-villa/models
type Post struct {
URL string `json:"url,omitempty"`
Caption string `json:"caption,omitempty"`
Likes []models.User `json:"likes,omitempty"` //您可以像这样使用它
}
您可以参考官方Go开发文档中的[链接][1]。在这里,您将获得“从您的模块导入包”的信息。
[1]: https://go.dev/doc/code
<details>
<summary>英文:</summary>
I have created a sample structure for your scenario as follows:
Assuming the Project Structure look like something this:
project-villa/ //Name of your Project
model/
-user.go //this file will contain your User Structure
repository/
-post.go //this file will hold your Post structure and the rest piece of code
handler/
driver/
main.go
Step1:- initialize the module
go mod init project-villa
OR
go mod init github.com/user-name/project-villa
The mod will manage the module dependency itself. Anyhow if it doesn't you can import it explicitly.
It will look like this:
github.com/random/project-villa/models
type Post struct {
URL string `json:"url,omitempty"`
Caption string `json:"caption,omitempty"`
Likes []models.User `json:"likes,omitempty"` //you can use it like this
}
For the reference you can follow the [1] of official go dev. Here you will get the `Importing packages from your module`.
[1]: https://go.dev/doc/code
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论