Correct import of package

Hi,

I am using Go v 1.12 and have created 2 projects (using GoLand but I do not think it matters) using Modules support: ~/temp/A and ~/temp/B. In B project I have a Go file with just one function which I want to call from the A project.

If using Dep (and inside the GOPATH/src folder), I have no problem to import B from A and use the function.

But with modules, what is the correct way to import that B package from project A?

Thanks a lot for any help!

Update!

Which AFAIK are only available since 1.11…

Ah sorry, I accidentally wrote 1.2. I use version 1.12.

I did a test that project A and B are essential packages in the same (~/temp) folder and modules are working ok, i.e. there is a single .mod file in the root (~/temp) folder. The problem is when A and B have not a common parent folder and thus (as separate projects) have their own .mod file.

I’m not using modules, but I took a look into the first iteration of before it was even joined into go project.

Back then, the project you want to import has if course be available somewhere and downloadable under its canonical name.

I tried to do something like this: (in projects’s A .mod file)

module A

go 1.12

require B v0.0.0
replace B v0.0.0 => …/B


and then, in A’s main.go file:

import “B”

but I get: “Cannot resolve file B”…

To be discoverable, the name of a go-module has to be a schemaless URL, which resolves to a git (or any other supported VCS) repository. Also this of course your code has to be published there.

Also, as far as I read the sparse comments about replace directive, you need to write it without the version, also you should only use two dots to go up a level of folders.

The dots are actually 2 but somehow the editor here puts another one…Tried to edit it but it keeps showing 3 dots.

I based my code on here: https://stackoverflow.com/questions/52026284/accessing-local-packages-within-a-go-module-go-1-11

Also, do you mean that I have to put my code on Git for this to work??

I think if your project is put under your GOPATH, the modules should be resolved correctly.

Hi Ivan,

I put the code outside of GOPATH intentionally as this is the goal of Go modules!

PS: The following works for me:

$ cat a/go.mod
module a

go 1.12

replace b => ../b

require b v0.0.0-00010101000000-000000000000 // indirect
$ cat a/main.go
package main

import (
	"b"
	"fmt"
)

func main() {
	fmt.Println(b.Foo())
}
$ cat b/go.mod
module b

go 1.12
$ cat b/foo.go
package b

func Foo() string {
	return "Foo in b"
}

Norbert, a million thank you for your help! From your solution I realised that I had to uncheck the “Vendoring mode support” in GoLand’s project settings (for Go modules support)…Now the project works as expected. Do you have any idea how I can achieve the same but when the projects have their vendor folder present?

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