【问题标题】:How to Import Local Package in Golang如何在 Golang 中导入本地包
【发布时间】:2022-01-08 13:31:38
【问题描述】:

我有问题。我无法在我的应用程序中导入本地包。


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"`
}

【问题讨论】:

  • 请参阅go.dev/doc/code 获取有关如何开发 Go 模块的教程。文档中的一个部分描述了如何使用同一模块中的包。

标签: go import package local


【解决方案1】:

我为您的场景创建了一个示例结构,如下所示:

假设项目结构如下所示:

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:- 初始化模块

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"` //you can use it like this
}

参考官方go dev的link。在这里你会得到Importing packages from your module

【讨论】:

    猜你喜欢
    • 2020-09-12
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多