Golang中如何导入本地包

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

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

假设项目结构如下所示:

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

go mod init project-villa

go mod init github.com/user-name/project-villa

mod 将管理 module 依赖本身。无论如何,如果没有,您可以显式导入它。 它看起来像这样:

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.