0

I have a project I am working on named project1.
Couple of months ago I worked on project2 which contains package named engine and I want to use it inside project1.
These projects are local so I read here how to import local projects and tried it but received an error:

Cannot resolve file `project2`

One interesting thing is that when I type the name of project2 in the import(..) section, Goland identify it as module but after I press on it I received the error that it can't be resolve.

With Goland I have an option to run sync packages of 'project1' but when I pressed on it I also received an error:

project1/pkg/utils imports
    project2: cannot find module providing package project2

I also tried to create vendor folder in project1 and copy-paste the whole project2 beneath the vendor folder but it still didn't help.

Any idea why it doesn't being resolve ?

E235
  • 11,560
  • 24
  • 91
  • 141

1 Answers1

1

If you have both of your projects under your $GOPATH, you can check out this example for importing projects.

EDIT: If you are using go modules and want to import local modules, then you can make use of the replace directive. So, basically you have to add in your go.mod of your Project1 these lines:

require /$module-name-project2/$package-name v0.0.0

replace $module-name-project2/$package-name => ../$localpath-to-project2

More info here

A quick example (both my projects are outside of $GOPATH and using go modules):

  1. Project1 is located under .../go-experiments/project1

main.go:

package main

import "go-experiments/project2/greeting"

func main() {
    println("How to greet?")

    greeting.English()
}

go.mod:

module go-experiments/project1

require go-experiments/project2/greeting v0.0.0

replace go-experiments/project2/greeting => ../project2

go 1.14
  1. Project2 is located under .../go-experiments/project2 greeter.go:
package greeting

func English() {
   println("hi, i am boo")
}

go.mod:

module go-experiments/project2

go 1.14
fabem
  • 156
  • 6
  • I already did it `import "project2"` but it wrote be the errors that I wrote on the question – E235 Apr 19 '20 at 11:11
  • Are you using gomodules? – fabem Apr 19 '20 at 11:22
  • 1
    I have edited my answer - check it out if this helps you :) – fabem Apr 19 '20 at 12:00
  • 1
    Thanks for your elaborated answer! It worked. I just needed to add `project2/engine v0.0.0` to `require` and add `replace project2/engine => ../project2` to `go.mod` and now it recognized it. – E235 Apr 19 '20 at 13:54
  • Only problem I see here is that this will create restrictions on how code is structured by anyone who wants to re-use the module created by you. From go1.13 and above we can re-use local file locations as goproxy. But, unfortunately there is no proper tooling to use the same right now. – praveent Apr 20 '20 at 09:05