Why don't we use Relative import paths?

I have read a few about sources “Relative import paths. This is unusual when writing a Go application.”

All right so How do I use correctly?

For example
import (
“app/controllers”
“app/handlers”
“app/helpers”
“context”
“database/sql”
“fmt”
“log”
“net/http”
“os”
“os/signal”
“syscall”
“time”

	_ "github.com/mattn/go-sqlite3"
)

I don’t see any relative imports there, just some app/... packages, that are not standard and might therefore fail to work eventually.

Relative imports start with at least one dot.

How to make standardize app/... packages ?

What do you mean?

Those are not in the standard lib, and I doubt you get them into it.

Just move them into a proper namespace.

1 Like

A few reasons why relative is a costly idea in Go and you had just demonstrated a few of them:

  1. confused from standard packages with relative packages. (demonstrated)
  2. additional cost to learn how to manage relative packages. (demonstrated)
  3. breaks go get in a number of ways. (demonstrated)
  4. complicates your developer’s documentation / manual.

Packages that don’t start with a version control system (vcs) URL are known to be standard packages (those that were installed together with Go compiler).

In today’s Go module, to import a relative local package using the pathing like a standard package, you need to define your replace statement inside your go.mod. The pattern is like:

replace (
        <import path> => <relative path>
)

Example:

replace (
        relative/core12 => ../core12
)

Then in your source codes, you do the natural import like:

import (
        "relative/core12"
)

This is not the recommended practice. In fact, it is a hack and abuse of feature. The recommended practice is to use internal directory so that you can abstract your software library gradually and possibly export it out as an independent package.

https://golang.org/doc/go1.4#internalpackages

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.