Oleksandr Dashkov
Oleksandr Dashkov

Reputation: 2848

How to make a short/relative import

Is it possible to make a relative import in Go code? I read a lot of examples but I really can't understand how to make it. For example, I have a project app and a sub package utils in it.

app
   main.go
   utils
        utils.go

utils.go:

package utils

import "fmt"

func TestFunc()  {
    fmt.Print("I'm a TestFunc")
}

Is there a way to import this package using only import "./utils" or import "app/utils but not take all the path like import "github.com/hithubuser/app/utils"?

If there is no way to do it, how do you work with the nested packages? Do you write a full the path for all the imports or you avoid to make it?

Upvotes: 1

Views: 1434

Answers (2)

jeevatkm
jeevatkm

Reputation: 4791

Typically import path starts after $GOPATH/src, refer to doc.

Let's say you have directory structure:

$GOPATH/src/github.com/hithubuser/app/utils

# your import path is 'github.com/hithubuser/app/utils'

Do you write a full the path for all the imports or you avoid to make it?

Yes, generally full import is used, since it enables you to distribute your code as go library. So that you can develop reusable code and import it in any project as needed or you can publish it to Go community.


Let's say you have standalone project, not referred to any other Go project and you're distributing as binary instead of go library. Then you can to something like this (it is not commonly used/recommended though).

Just git clone your repo at $GOPATH/src like git clone github.com/hithubuser/app

$GOPATH/src/app/utils

# then import path is app/utils

Upvotes: 4

user539810
user539810

Reputation:

Another possibility is to use the vendor facilities introduced in Go 1.5.

  1. Create a vendor directory.
  2. Copy (or git clone or whatever) your utils directory as a subdirectory of vendor, so your hierarchy now looks like this:

    app
    |-- main.go
    `-- vendor/
        `-- utils/
            `-- utils.go
    
  3. Set the GO15VENDOREXPERIMENT environment variable to 1 to enable vendoring support if you're using Go 1.5. Newer versions enable it by default.

Upvotes: 1

Related Questions