Import local package

My project structure looks like this:

--/project
----main.go
----/models
------user.go

      

In main.go I want user user.go:

user.go:

package models

type User struct {
    Name string
}

      

main.go:

package main

import (...)

func main() {
    user := &User{Name: "Igor"}
}

      

How do I import user.go from main.go?

/ project is under the GOPATH, so I tried:

import "project/models"

      

but that doesn't do anything.

+3


source to share


2 answers


Your installation is correct, you are using the package incorrectly.

changes:

user := &User{Name: "Igor"}

      

in



user := &models.User{Name: "Igor"}

      

or if you don't want to always say models.XXX, change your imports.

import . "project/models"

      

I find this makes the code harder to read in the long run. It is obvious to the reader where "models.User" comes from, not just a regular "user" as usual, it means that it comes from this package.

+7


source


If you are building a project outside of a go workspace, you can use relative imports :

import "./models"

      



However, using relative imports is not a good idea. The preferred way is to import the full package path (and place your project in the correct go workspace ):

import "github.com/igor/myproject/models"

      

+2


source







All Articles