Search code examples
goimportpackagelocal

How to Import Local Package in Golang


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

Solution

  • 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 link of official go dev. Here you will get the Importing packages from your module.