Timur Fayzrakhmanov
Timur Fayzrakhmanov

Reputation: 19587

How to import packages between themselves under one repository in golang?

I want to understand how to import packages correctly in the example beyond.

I've read this topic (How to use custom packages in golang?), but it doesn't explain what I'm trying to understand.

For example, I want to create package for further using it in my program and publishing at github.com. This is how the code should be organized in my view:

src/
  github.com/
    username/
      repository/
        lib1.go #package repository
        lib2.go #package repository
        sublib/
          sublib1.go #package sublib
          sublib2.go #package sublib
      ...

  myproject/
    programname.go #package main
    #there is no problem how to import my repository here:
    #import "github.com/username/repository"
    #or import "github.com/username/repository/sublib" 

Ok, at this point I want to understand how can I import repository's code in the repository/sublib and vise versa. I think question is more aimed for internal importing (under one repository).

First solution is obviously - importing packages by fullpath:

Hmm, but what if I change path in the future? May be there is better way for importing internal packages.. Also I'm faced with a problem when I import github.com/username/repository in the sublib1.go (I get the error message import cycle not allowed).

I hope I've explained quite ok to get this question.

Upvotes: 3

Views: 3425

Answers (2)

VonC
VonC

Reputation: 1324935

import "github.com/username/repository/sublib" is the way to go: as I mentioned in "Is it possible don't specify package name?", the other "solution" would be

import "./sublib"

That is using a relative path, which is not considered a good practice, as explained in "Go language package structure" and "Golang how to import local packages without gopath?".

If you change path in the future, the issue will be similar with absolute or relative import paths, but the first (absolute) paths remains "go-gettable" by other people.

Upvotes: 1

Evan
Evan

Reputation: 6545

You cannot have circular imports in Go, they are explicitly disallowed. Your only option is to rethink the way you are splitting up your packages so there are no loops.

Upvotes: 2

Related Questions